@viewChild返回未定义的角度

时间:2020-08-03 09:36:22

标签: angular viewchild

我已经阅读了其他与我相似的帖子,但是它们之间没有完全关联,因此我要求我提供具体案例。 当我尝试使用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!'

}

我遵循了官方的角度文档,怎么了?谢谢!

1 个答案:

答案 0 :(得分:1)

read属性用于区分几个可用的可注入项(不能将其设置为布尔值)。 您无需在用例中使用它。 将其删除即可。

为避免出现expression has changed after it was checked错误,请手动运行更改检测:

constructor(cdr: ChangeDetectorRef) {}

ngAfterViewInit() {
    this.childMessage = this.child.message;
    this.cdr.detectChanges();
  }