Access Child Components From the Template
In our templates, we may find ourselves needing to access values provided by the child components which we use to build our own component.
The most straightforward examples of this may be seen dealing with forms or inputs:
app/app.component.html
<section >
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<label for="name">Name</label>
<input type="text" name="name" id="name" ngModel>
<button type="submit">Submit</button>
</form>
Form Value: {{formValue}}
</section>
app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'rio-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
formValue = JSON.stringify({});
onSubmit (form: NgForm) {
this.formValue = JSON.stringify(form.value);
}
}
This isn't a magic feature which only forms or inputs have, but rather a way of referencing the instance of a child component in your template. With that reference, you can then access public properties and methods on that component.
app/app.component.html
<rio-profile #profile></rio-profile>
My name is {{ profile.name }}
app/profile.component.ts
@Component({
selector: 'rio-profile',
templateUrl: 'app/profile.component.html'
})
export class ProfileComponent {
name = 'John Doe';
}
There are other means of accessing and interfacing with child components, but if you simply need to reference properties or methods of a child, this can be a simple and straightforward method of doing so.