Angular Material Select -想要将垫子选项的值链接到更大的输出


<mat-form-field appearance="fill">
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected">
<mat-option>None</mat-option>
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
</mat-form-field>
<p>You selected: {{selected}}</p>

如果我选择其中一个值,我希望输出多于选项1,2,3,3。所以应该显示更大的文字。所以我想选择一个段落的数字,然后输出整个段落,如果选择。我怎么才能做到呢?

你需要得到你的段落,并将所有的数组。接下来需要在模板中使用*ngFor操作符来迭代所有段落列表。看看我的例子:

<mat-form-field appearance="fill">
<mat-label>Select</mat-label>
<mat-select>
<!-- // here is we doing iteration all of paragraphs -->
<ng-container *ngFor="let item of paragraphs">
<mat-option value="item?.line"> {{ item?.name }}</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
<!-- increasing array length -->
<button mat-button (click)="addItems()"> Add Item</button>

和typescript代码

import {Component} from '@angular/core';
interface Paragraph {
line: number;
name: string;
};
/** @title Simple form field */
@Component({
selector: 'form-field-overview-example',
templateUrl: 'form-field-overview-example.html',
styleUrls: ['form-field-overview-example.css']
})
export class FormFieldOverviewExample {

paragraphs : Paragraph[] = [];
constructor () {
this.paragraphs = [
{ line: 1, name: 'P1'},
{ line: 2, name: 'P2'},
{ line: 3, name: 'P3'}
];
}
addItems() {
this.paragraphs.push( {line: this.paragraphs.length+1, name: 'P'+(this.paragraphs.length+1)})
}
}

我理解你的问题,这里的目的是在实际的垫子选择下面显示一个更大的段落,这取决于当前选择的值。有几种方法可以实现这一目标。既然你使用的不是数组,而是html模板,你可以使用ngSwitchCase指令:https://angular.io/api/common/NgSwitchCase

的例子:

<mat-form-field appearance="fill">
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected">
<mat-option>None</mat-option>
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
</mat-form-field>
<div [ngSwitch]="selected">
<p *ngSwitchCase="'option1'">Your long text 1 here</p>
<p *ngSwitchCase="'option2'">Your long text 2 here</p>
<p *ngSwitchDefault>Text when nothing is selected.</p>
</div>

最新更新