无法从Angular组件的父组件访问子组件

时间:2018-10-26 16:09:44

标签: angular

我是新手。因此,可能由于缺乏经验,我错过了重要的东西。请帮助我从父级访问子级组件。

app.module.ts

import { FilePickerComponent } from "src/app/common/file-picker/file-picker.component";
...
@NgModule({
  declarations: [
  FilePickerComponent,
  ...
  ]})
export class AppModule {}

file-picker.component.ts

...
@Component({
  selector: "app-file-picker",
  templateUrl: "./file-picker.component.html",
  styleUrls: ["./file-picker.component.css"],  
})
...

editor.html

<form>
    ...
    <app-file-picker
        placeholder="Image"        
        required>
    </app-file-picker>
    ...
</form>

editor.ts

import {
  Component,
  OnInit,
  ViewChild,
  OnDestroy
} from "@angular/core";

import { FilePickerComponent } from "src/app/common/file-picker/file-picker.component";

export class Editor implements OnInit, OnDestroy {

@ViewChild(FilePickerComponent) filePicker!: FilePickerComponent;
async save() {

}
当我尝试从保存访问文件选择器时,

尚未定义。如何从editor.ts访问文件选择器组件?

3 个答案:

答案 0 :(得分:1)

export class Editor implements OnInit, OnDestroy {

@ViewChild(FilePickerComponent) filePicker!: FilePickerComponent;
async save() {

}

在上面的代码中缺少AfterViewInit生命周期挂钩的实现。在角度文档中,它指出此生命周期挂钩很重要。

enter image description here

Angular documentation for component intreactions

尝试如下更改上面的代码

import {
  Component,
  OnInit,
  ViewChild,
  OnDestroy,
  AfterViewInit
} from "@angular/core";


export class Editor implements OnInit, OnDestroy,AfterViewInit {

@ViewChild(FilePickerComponent) filePicker!: FilePickerComponent;
async save() {

}

答案 1 :(得分:0)

尝试一下

<app-file-picker #filePicker>

</app-file-picker>

然后在父组件中引用#filePicker,如下所示:

@ViewChild("filePicker")

答案 2 :(得分:0)

  

您的代码看起来不错,除了小的syntactical校正。从变量!中删除filePicker标记。

更改以下代码

@ViewChild(FilePickerComponent) filePicker!: FilePickerComponent;

@ViewChild(FilePickerComponent) filePicker: FilePickerComponent;