I'm learning Angular, i need to pass a select value to a "p" in another component. So when the value of the select changes the "p" element also changes.
app.component.html
<navbar></navbar> <todo-list-cards></todo-list-cards> <test></test> <router-outlet></router-outlet>
todo.component.html
<div class="contenedorTareas"> <div class="card text-white bg-primary mb-3" id="cards" style="max-width: 18rem;"> <div class="card-header">Header</div> <div class="card-body"> <h5 class="card-title">Primary card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <select name="selector" id="selector"> <option>Option 1</option> <option>Option 2</option> </select> </div> </div> <div class="cards"> <div class="card text-white bg-primary mb-3" style="max-width: 18rem;"> <div class="card-header">Header</div> <div class="card-body"> </div> </div> </div> </div>
test.component.html
<p><!-- Here the value of the <select> should be--></p>
Best in my opinion is to bind the selected value and the paragraph content using a service. Try adding todo.service.ts with the following:
private selected: string;
public get selectedValue() {
return this.selected;
}
public setSelectedValue(value: string){
this.selected = value;
}
Then, in todo update the value in the service, and in test simply get it into the
:
<p>{{todoService.SelectedValue}}</p>
test.component.ts (child component)
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
})
export Class TestComponent {
@Input() selectedOption: string;
}
Now use that input in your html file.
test.component.html
<p>{{selectedOption}}</p>
When you include your test component in a parent component ie todo.component.html you can pass input selectedOption from parent to child as [input] in html tag
<div class="contenedorTareas">
<div class="card text-white bg-primary mb-3" id="cards" style="max-width: 18rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h5 class="card-title">Primary card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's
content.</p>
<select [(ngModel)]="optionSelected" name="selector" id="selector">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
</div>
<div class="cards">
<div class="card text-white bg-primary mb-3" style="max-width: 18rem;">
<div class="card-header">Header</div>
<div class="card-body">
</div>
</div>
</div>
</div>
<app-test [selectedOption]="optionSelected"></app-test>
todo.component.ts parent component
export class TodoComponent {
optionSelected: string;
}
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.