Angular の@ViewChildの使い方
Angular の@ViewChildを使えば、parent to view child というように親コンポーネントから子コンポーネントのメソッドなどにアクセスできるようになります。
またコンポーネントの#変数にアクセスできるようになります。
例えば子要素の数を知りたい場合、親要素に#変数を付加します。この変数がViewChildと紐づきます。
app.component.html
<div #aaa> <ul> <li></li> <li></li> </ul> </div> <button type='button' (click)='onTest()'>ボタン</button>
app.component.ts
import { Component, ViewChild, ElementRef} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { @ViewChild('aaa') ppp: ElementRef; public onTest() { const elem: Element = this.ppp.nativeElement;// これがdivタグを指す alert(elem.childElementCount); // 子要素の数を取得する } }
onTestイベントハンドラが@ViewChildを使ってdivタグの情報を取得できているのがわかります。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
コメント