Angualr 指令

189 阅读4分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第26天,点击查看活动详情

在Angular中指令可以修改DOM结构,用于更改DOM元素的外观,行为或布局, 指令是Angular 2用于构建应用程序的核心模块之一,包括Angular 2组件它的本质就是带有模板的特殊指令。

Angular 2中有三种主要类型的指令:

  1. Component(组件) - 指令与模板
  2. Attribute directives(属性指令) -更改组件或元素的行为但不影响模板的指令
  3. Structural directives(结构指令)- 通过影响模板的呈现方式来改变组件或元素的行为的指令

一、属性指令

属性指令是改变组件的外观和行为的一种实现方式,指令应该以挂载在组件的方式工作,而不是绑定到具体实现的细节,Angular 2内置的属性指令ngClassngStyle,可以在所有宿主组件上挂载。

1.NgStyle 指令

Angular 2的一个内置的指令ngStyle来修改组件或P标签元素的style属性

@Component({
    selector: 'app-style-example',
    template: `
      <p [ngStyle]="{'borderBottom': borderStyle}">
        <ng-content></ng-content>
      </p>
    `
  })
  export class StyleExampleComponent {
    //样式
    borderStyle = '1px solid black';
}

绑定指令的方式与组件属性绑定是相同的 ,我们将一个表达式和一个对象字面量绑定到ngStyle指令,指令名称必须用方括号括起来。 ngStyle接受一个对象,属性和值定义该元素的样式,当指定style属性时,我们可以使用短横线式(kebab case)和小驼峰式(lower camel case)来对属性命名,在对元素进行样式设计时,html的style 属性和Angular ngStyle指令都是合并执行的。

我们可以将样式属性从模板中移除到组件中作为属性对象,然后使用属性绑定将其分配给NgStyle。 这允许对值的动态更改,而且让添加和删除样式属性更加灵活。

 @Component({
    selector: 'app-style-example',
    template: `
      <p style="padding: 1rem"
        [ngStyle]="alertStyles">
        <ng-content></ng-content>
      </p>
    `
  })
  export class StyleExampleComponent {
    borderStyle = '1px solid black';
    alertStyles = {
      'color': 'red',
      'font-weight': 'bold',
      'borderBottom': this.borderStyle
    };
  }
2.NgClass 指令

ngClass指令更改绑定到宿主组件或元素的class属性,有多种不同的方式使用指令。

1.绑定一个字符串

我们可以直接将一个字符串绑定到属性。这就像添加一个htmlclass属性一样。

@Component({
    selector: 'app-class-as-string',
    template: `
      <p ngClass="centered-text underlined" class="orange">
        <ng-content></ng-content>
      </p>
    `,
    styles: [`
      .centered-text {
        text-align: center;
      }
      .underlined {
        border-bottom: 1px solid #ccc;
      }
      .orange {
        color: orange;
      }
    `]
  })
  export class ClassAsStringComponent {
  }

在这种情况下,我们直接绑定一个字符串,所以我们避免使用方括号包装指令。还要注意ngClass使用class属性来组合最终的类。

2.绑定一个数组

@Component({
    selector: 'app-class-as-array',
    template: `
      <p [ngClass]="['warning', 'big']">
        <ng-content></ng-content>
      </p>
    `,
    styles: [`
      .warning {
        color: red;
        font-weight: bold;
      }
      .big {
        font-size: 1.2rem;
      }
    `]
  })
  export class ClassAsArrayComponent {
  }

在这里,由于我们使用表达式绑定到ngClass指令,我们需要在方括号中包装指令名称。当你想有一个函数放在适用的类名列表时,传入数组是很有用的。

3.绑定一个对象

最后,一个对象可以绑定到指令。如果该属性为true,Angular 2将该对象的每个属性名称应用于组件。

@Component({
  selector: 'app-class-as-object',
  template: `
    <p [ngClass]="{ card: true, dark: false, flat: flat }">
      <ng-content></ng-content>
      <br>
      <button type="button" (click)="flat=!flat">Toggle Flat</button>
    </p>
  `,
  styles: [`
    .card {
      border: 1px solid #eee;
      padding: 1rem;
      margin: 0.4rem;
      font-family: sans-serif;
      box-shadow: 2px 2px 2px #888888;
    }
    .dark {
      background-color: #444;
      border-color: #000;
      color: #fff;
    }
    .flat {
      box-shadow: none;
    }
  `]
})
export class ClassAsObjectComponent {
  flat: boolean = true;
}

二、结构指令

结构指令是处理组件或元素通过使用模板标签呈现的方式。 这允许我们运行一些代码来决定最终渲染的输出。 Angular 2有一些内置的结构指令,如ngIfngForngSwitch 结构化指令在模板中有自己的特殊语法。

@Component({
    selector: 'app-directive-example',
    template: `
      <p *structuralDirective="expression">
        Under a structural directive.
      </p>
    `
})

我们的伪结构伪指令不带方括号,而是带有星号。即使没有方括号,绑定仍然是表达式绑定。 因为它是语法糖,允许以更直观的方式使用指令,类似于在Angular 1中使用指令上面的组件模板等价于下面的代码:

@Component({
    selector: 'app-directive-example',
    template: `
      <template [structuralDirective]="expression">
        <p>
          Under a structural directive.
        </p>
      </template>
    `
  })

我们看到我们前面说的结构化指令使用的template 标签。 Angular 2也有一个做同样的事情的内置template 指令。

@Component({
    selector: 'app-directive-example',
    template: `
      <p template="structuralDirective expression">
        Under a structural directive.
      </p>
    `
})
1.NgIf 指令

ngIf指令可以根据表达式的逻辑真假进行有条件地选择渲染组件或元素,这对我们平时开发很有用,不用像传统js一样去用逻辑手动控制它显示或者隐藏。

@Component({
  selector: 'app',
  template: `
    <button type="button" (click)="toggleExists()">Toggle Component</button>
    <hr/>
    <if-example *ngIf="exists">
      Hello
    </if-example>
  `
})
export class AppComponent {
    //渲染条件
  exists: boolean = true;
  //点击改变条件
  toggleExists() {
    this.exists = !this.exists;
  }
}
2.NgFor 指令

ngFor指令是使用可循环迭代的每个选项作为模板的上下文来重复渲染模板的一种方式,例如下拉框和表格的行渲染都可以使用ngFor指令。

<nz-select>
   <nz-option *ngFor="let option of Languages" [nzValue]="option.Value"
                                      [nzLabel]="option.Name">
   </nz-option>
</nz-select>
​
Languages:any[]= [{Value:1,Name:"选项一"},{Value:2,Name:"选项二"}]
3.NgSwitch 指令

每一个元素上都有一个标签,我们利用标签中的值与最外层tab变量进行匹配,一旦匹配到对应元素就会渲染到界面,如果没有匹配那么就会渲染默认的第四个div块

 <div [ngSwitch]="tab" >
    <div  *ngSwitchCase="1" > 1 < /div>
    <div  *ngSwitchCase="2" > 2 < /div>
    <div  *ngSwitchCase="3" > 3 < /div >
    <div  *ngSwitchDefault > 4  < /div>
​
< /div>

\