呼び出したいメソッドを持つ子コンポーネントを作成しました。
このメソッドを呼び出すと、console.log()
行のみが起動され、プロパティは設定されませんtest
。
以下は、私が変更を加えたクイック スタート Angular アプリです。
親
import { Component } from '@angular/core';
import { NotifyComponent } from './notify.component';
@Component({
selector: 'my-app',
template:
`
<button (click)="submit()">Call Child Component Method</button>
`
})
export class AppComponent {
private notify: NotifyComponent;
constructor() {
this.notify = new NotifyComponent();
}
submit(): void {
// execute child component method
notify.callMethod();
}
}
子供
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'notify',
template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
test:string;
constructor() { }
ngOnInit() { }
callMethod(): void {
console.log('successfully executed.');
this.test = 'Me';
}
}
プロパティも設定するにはどうすればいいでしょうかtest
?
ベストアンサー1
@ViewChild
詳細については、こちらを参照してください。リンク
タイプセレクター付き
子コンポーネント
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
親コンポーネント
@Component({
selector: 'some-cmp',
template: '<child-cmp></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild(ChildCmp) child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}
文字列セレクター付き
子コンポーネント
@Component({
selector: 'child-cmp',
template: '<p>child</p>'
})
class ChildCmp {
doSomething() {}
}
親コンポーネント
@Component({
selector: 'some-cmp',
template: '<child-cmp #child></child-cmp>',
directives: [ChildCmp]
})
class SomeCmp {
@ViewChild('child') child:ChildCmp;
ngAfterViewInit() {
// child is set
this.child.doSomething();
}
}