angular

常见的Angular装饰器,持续更新中…...

2019-09-26  本文已影响0人  窗外的雪儿飞

1. @Attribute

顾名思义,是用来寻找宿主元素属性值的。

@Directive({
  selector: '[test]'
})
export class TestDirective {
  constructor(
    @Attribute('type') type
  ) {
    console.log(type); // text
  }
}
  
@Component({
  selector: 'my-app',
  template: `
    <input type="text" test>
  `,
})
export class App {}

2. @ViewChildren

@Component({
  selector: 'alert',
  template: `
    {{type}}
  `,
})
export class AlertComponent {
  @Input() type: string = "success";
}

@Component({
  selector: 'my-app',
  template: `
    <alert></alert>
    <alert type="danger"></alert>
    <alert type="info"></alert>
  `,
})
export class App {
  @ViewChildren(AlertComponent) alerts: QueryList<AlertComponent>
  
  ngAfterViewInit() {
    this.alerts.forEach(alertInstance => console.log(alertInstance));
  }
}

3. @ViewChild

和ViewChildren类似,但它只返回匹配到的第一个元素或与视图DOM中的选择器匹配的指令。

@Component({
  selector: 'alert',
  template: `
    {{type}}
  `,
})
export class AlertComponent {
  @Input() type: string = "success";
}

@Component({
  selector: 'my-app',
  template: `
    <alert></alert>
    <div #divElement>Tada!</div>
  `,
})
export class App {
  // 返回宿主元素
  @ViewChild("divElement") div: any;
  // 返回组件实例
  @ViewChild(AlertComponent) alert: AlertComponent;
  
  ngAfterViewInit() {
    console.log(this.div);
    console.log(this.alert);
  }
}

4. @ContentChildren

装饰器从Content DOM返回指定的元素或指令作为queryList,值得注意的是:

@Component({
  selector: 'tab',
  template: `
    <p>{{title}}</p>
  `,
})
export class TabComponent {
  @Input() title;
}

@Component({
  selector: 'tabs',
  template: `
    <ng-content></ng-content>
  `,
})
export class TabsComponent {
 @ContentChildren(TabComponent) tabs: QueryList<TabComponent>
 
 ngAfterContentInit() {
   this.tabs.forEach(tabInstance => console.log(tabInstance))
 }
}

@Component({
  selector: 'my-app',
  template: `
    <tabs>
     <tab title="One"></tab>
     <tab title="Two"></tab>
    </tabs>
  `,
})
export class App {}

5. @ContentChild

@ContentChildren类似,但仅返回与Content DOM中的选择器匹配的第一个元素或指令。

@Component({
  selector: 'tabs',
  template: `
    <ng-content></ng-content>
  `,
})
export class TabsComponent {
 @ContentChild("divElement") div: any;
 
 ngAfterContentInit() {
   console.log(this.div);
 }
}

@Component({
  selector: 'my-app',
  template: `
    <tabs>
     <div #divElement>Tada!</div>
    </tabs>
  `,
})
export class App {}

6. @HostBinding

声明一个属性绑定到hosts上。

@Directive({
  selector: '[host-binding]'
})
export class HostBindingDirective {
  @HostBinding("class.tooltip") tooltip = true;
  
  @HostBinding("class.tooltip") 
  get tooltipAsGetter() {
    // 你的逻辑
    return true;
  };
   
  @HostBinding() type = "text";
}

@Component({
  selector: 'my-app',
  template: `
    <input type="text" host-binding> // 'tooltip' class 将被添加到host元素上
  `,
})
export class App {}

7. @HostListener

敬请期待,学习中...

上一篇下一篇

猜你喜欢

热点阅读