Angular 8-在另一个组件中复制选择值

问题描述 投票:0回答:2

我正在学习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>
javascript html angular components
2个回答
0
投票

我认为最好是使用服务将所选值和段落内容绑定在一起。尝试使用以下命令添加todo.service.ts:

private selected: string;
public get selectedValue() {
    return this.selected;
  }
public setSelectedValue(value: string){
    this.selected = value;
}

然后,在todo中更新服务中的值,并在测试中将其放入

<p>{{todoService.SelectedValue}}</p>

0
投票

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.