angular ViewChild ContentChild 系列的查詢參數


官方說明

官方文檔
在調用 NgAfterViewInit 回調函數之前就會設置這些視圖查詢。
元數據屬性:

  • selector - 用於查詢的指令類型或名字。
  • read - 從查詢到的元素中讀取另一個令牌。

所支持的選擇器包括:

  • 任何帶有 @Component 或 @Directive 裝飾器的類
  • 字符串形式的模板引用變量(比如可以使用 @ViewChild('cmp') 來查詢 <my-component #cmp>
  • 組件樹中任何當前組件的子組件所定義的提供商(比如 @ViewChild(SomeService) someService: SomeService )
  • 任何通過字符串令牌定義的提供商(比如 @ViewChild('someToken') someTokenVal: any )
  • TemplateRef(比如可以用 @ViewChild(TemplateRef) template; 來查詢

代碼:

<div #testBox [appElementTitle]="'屬性指令測試'" [appCopyAttr]="'https://liangyuetian.cn/'">
    appElementTitle 屬性指令測試 appCopyAttr 屬性指令測試
</div>
<div #box [appElementTitle]="'這是box的title'" [appCopyAttr]="'https://baidu.com.cn/'">
    appElementTitle 屬性指令測試 appCopyAttr 屬性指令測試
</div>
export class AppComponent implements OnInit, AfterViewInit {
    @ViewChild('testBox', {read: ElementRef}) elBox: ElementRef;
    @ViewChild('testBox', {read: CopyAttrDirective}) copy: CopyAttrDirective;
    @ViewChild('testBox', {read: ElementTitleDirective}) titles: ElementTitleDirective;

    @ViewChild('box', {read: ElementRef}) elBox2: ElementRef;
    @ViewChild('box', {read: CopyAttrDirective}) copy2: CopyAttrDirective;
    @ViewChild('box', {read: ElementTitleDirective}) titles2: ElementTitleDirective;

    keyUpSearch($event: { [key: string]: any }) {
        console.log($event.code, $event.key, $event);
    }
    ngOnInit() {
    }
    ngAfterViewInit() {
        console.log('one', this.elBox, this.copy, this.titles);
        console.log('tow', this.elBox2, this.copy2, this.titles2);
    }
}

效果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM