angular 常用指令

本文介绍了Angular中常用的ngIf与ngFor指令的基本用法及示例代码。ngIf用于根据条件动态显示或隐藏元素;ngFor则用于遍历集合并为每个元素生成指定的模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自 http://www.ngui.cc/news/show-104.html

在 Angular 实际项目中,最常用的指令是 ngIf 和 ngFor 指令。

基础知识

ngIf 指令简介

该指令用于根据表达式的值,动态控制模板内容的显示与隐藏。它与 AngularJS 1.x 中的 ng-if 指令的功能是等价的。

ngIf 指令语法
<div *ngIf="condition">...</div>
ngFor 指令简介

该指令用于基于可迭代对象中的每一项创建相应的模板。它与 AngularJS 1.x 中的 ng-repeat 指令的功能是等价的。

ngFor 指令语法
<li *ngFor="let item of items;">...</li>

ngIf 与 ngFor 指令使用示例

import { Component } from '@angular/core';
 interface Address {
    province: string;
    city: string;
} 
@Component({
    selector: 'sl-user',
    template: `
    <h2>大家好,我是{{name}}</h2>
    <p>我来自<strong>{{address.province}}</strong>省,
      <strong>{{address.city}}</strong>市
    </p>
    <div *ngIf="showSkills">
        <h3>我的技能</h3>
        <ul>
            <li *ngFor="let skill of skills">
                {{skill}}
            </li>
        </ul>
    </div>
    ` }) 
export class UserComponent {
    name: string;
    address: Address;
    showSkills: boolean;
    skills: string[]; 
 constructor() { 
 this.name = 'Semlinker'; 
 this.address = {
            province: '福建',
            city: '厦门' };
       this.showSkills = true; 
 this.skills = ['AngularJS 1.x', 'Angular 2.x', 'Angular 4.x'];
    } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值