我正在尝试探究角度。这是我的角度代码。
HTML组件
<mat-form-field class="select-country-component">
<mat-label>Select Country</mat-label>
<mat-select id="countries" class="tar-selector" (selectionChange)="getCountryDetails($event.value)">
<mat-option *ngFor="let country of countries" [value]="country.id">
{{country.name}}
</mat-option>
</mat-select>
</mat-form-field>
为什么要加载,如果本地存储中保存了任何值,那么我想从班级中设置选择框值。
TS代码
ngOnInit() {
if (localStorage.getItem("COUNTRYSELECTED") !=""){
// set value of localStorage.getItem("COUNTRYSELECTED") here
}
如何以简单的方式实现这一目标?
答案 0 :(得分:0)
您可以使用ngModel中的FormsModule伪指令进行双向数据绑定:
@Component({
template: `
<mat-form-field class="select-country-component">
<mat-label>Select Country</mat-label>
<mat-select id="countries" class="country-selector" [(ngModel)]="value" (ngModelChange)="getCountryDetails($event)">
<mat-option *ngFor="let country of countries" [value]="country.id">
{{country.name}}
</mat-option>
</mat-select>
</mat-form-field>
`
}) class MyComponent {
value: string;
countries = [];
ngOnInit() {
if (localStorage.getItem("COUNTRYSELECTED")){
this.value = localStorage.getItem("COUNTRYSELECTED");
}
}
getCountryDetails(countryId: string) {
// some code
}
}