@viewChild return 在 Angular 中未定义
@viewChild return undefined in Angular
我已经看过其他类似的帖子,但它们并不完全相关,所以我问一下我的具体情况。
当我尝试在控制台中获取 child.message 的值或打印 child 时,出现 'child is undefined' 错误。
app.component.ts
@Component({
selector: 'app-root',
template: `
<h1>Example of uses of @ViewChild with child component</h1>
<app-child-component></app-child-component>
<p>This is the message value of the child component selected with @ViewChild: '{{childMessage}}' </p>
`
})
export class AppComponent implements AfterViewInit{
@ViewChild(ChildComponent, { read: true }) child!: ChildComponent
childMessage:string
ngAfterViewInit(){
console.log(this.child)
this.childMessage = this.child.message
}
}
child.component.ts
@Component({
selector: 'app-child-component',
template: `
<div class="container">
<h2>This is the child component!</h2>
<p> The message value is '{{message}}'</p>
</div>
`,
styles: ['.container{ background-color: rgb(154, 218, 226); border: 1px solid black; }']
})
export class ChildComponent {
message:string = 'Ave Caesar!'
}
我按照官方angular文档,怎么了?谢谢!
read
属性 用于区分几个可用的可注射项目(顺便说一下,它不能设置为布尔值)。
您的用例中不需要它。
它会通过删除它来工作。
为避免expression has changed after it was checked
错误,运行手动更改检测:
constructor(cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.childMessage = this.child.message;
this.cdr.detectChanges();
}
我已经看过其他类似的帖子,但它们并不完全相关,所以我问一下我的具体情况。 当我尝试在控制台中获取 child.message 的值或打印 child 时,出现 'child is undefined' 错误。
app.component.ts
@Component({
selector: 'app-root',
template: `
<h1>Example of uses of @ViewChild with child component</h1>
<app-child-component></app-child-component>
<p>This is the message value of the child component selected with @ViewChild: '{{childMessage}}' </p>
`
})
export class AppComponent implements AfterViewInit{
@ViewChild(ChildComponent, { read: true }) child!: ChildComponent
childMessage:string
ngAfterViewInit(){
console.log(this.child)
this.childMessage = this.child.message
}
}
child.component.ts
@Component({
selector: 'app-child-component',
template: `
<div class="container">
<h2>This is the child component!</h2>
<p> The message value is '{{message}}'</p>
</div>
`,
styles: ['.container{ background-color: rgb(154, 218, 226); border: 1px solid black; }']
})
export class ChildComponent {
message:string = 'Ave Caesar!'
}
我按照官方angular文档,怎么了?谢谢!
read
属性 用于区分几个可用的可注射项目(顺便说一下,它不能设置为布尔值)。
您的用例中不需要它。
它会通过删除它来工作。
为避免expression has changed after it was checked
错误,运行手动更改检测:
constructor(cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.childMessage = this.child.message;
this.cdr.detectChanges();
}