0

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?

1
  • so, from this, you will need to something like: @ViewChild(<some-id>) userEdit: ElementRef; and also add the id #<some-id> to the directive Commented May 22, 2020 at 13:15

1 Answer 1

2

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',
   ...
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.