我正在学习Angular,我需要将选择值传递给另一个组件中的“ p”。因此,当select的值更改时,“ p”元素也会更改。
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>
我认为最好是使用服务将所选值和段落内容绑定在一起。尝试使用以下命令添加todo.service.ts:
private selected: string;
public get selectedValue() {
return this.selected;
}
public setSelectedValue(value: string){
this.selected = value;
}
然后,在todo中更新服务中的值,并在测试中将其放入
:
<p>{{todoService.SelectedValue}}</p>
test.component.ts(子组件)
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
})
export Class TestComponent {
@Input() selectedOption: string;
}
现在在您的html文件中使用该输入。
test.component.html
<p>{{selectedOption}}</p>
[当您将测试组件包括在父组件中时,即todo.component.html您可以将输入的selectedOption从父项传递到子项,作为html标记中的[input
<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父组件
export class TodoComponent {
optionSelected: string;
}