简体   繁体   中英

Failing to access child component using ViewChild in Angular

I have a dialog box that is displaying a separate child component. The child component is below:

@Component({
  selector: 'userEdit',
  templateUrl: './edituser.component.html',
  styleUrls: ['./edituser.component.css']
})
export class EditUserComponent implements OnInit {
  public theName: string;
  public theAddress: string;

  constructor() {
    this.theName = '';
    this.theAddress = '';
  }

  ngOnInit() {
  }

}

The dialog box code and template are below:

@Component({
  selector: 'app-userdialog',
  templateUrl: './userdialog.component.html',
  styleUrls: ['./userdialog.component.css']
})
export class UserDialogComponent implements OnInit {
  @ViewChild('userEdit', {static: false})
  userEdit: EditUserComponent;

  constructor(
    public dlgRef: MatDialogRef<UserDialogComponent>,
   @Inject(MAT_DIALOG_DATA) public theData: UsrStuff) { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    console.log('Name: ' + this.userEdit.theName);
  }

  addUser() {
  // TODO: implement adding a user
 }

  closeBox() {
    this.dlgRef.close();
  }
}

and

<div id="attribdlg">
    <h3>Add New User</h3>
    <userEdit theName="" theAddress=""></userEdit>
    <mat-dialog-actions>
        <button mat-raised-button color="primary" (click)="addUser()">Add User</button>
        <button mat-raised-button color="primary" (click)="closeBox()">Done</button>
    </mat-dialog-actions>
</div>

Based on the documentation and examples Ihave seen, this setup should enable me to print to the console the value pf userEdit's theName property in the ngAfterViewInit() function.

Unfortunately, this does not appear to be working.When the console log is called, I get the following failure message:

null: TypeError: Cannot read property 'theName' of undefined

Obviously, there is some kind of initialization of the child component that is supposed to happen, but I do not see this being done anywhere in the documentation. I am missing something.

How can I get this child component and its properties available to my dialog?

Two options:

  1. Set an id to the component you wish to have with ViewChild() :

TypeScript:

@ViewChild('userEdit', {static: false})

HTML:

<userEdit #userEdit theName="" theAddress=""></userEdit>
  1. Select by directive or component :

TypeScript:

@import { EditUserComponent } from '...';

@ViewChild(EditUserComponent, {static: false})

HTML:

<userEdit theName="" theAddress=""></userEdit>
  • I highly recommend you to use app perfix for the component's selector !!!
@Component({
   ...
      selector: 'app-user-edit',
   ...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM