Angular 7 Material 动态检查更新单选按钮
Angular 7 Material Updating Radio Button checked dynamically
我有一个带有单选按钮的 Angular Material 应用程序。我想根据数据库中的数据更新所选按钮。一切正常,除了选中的按钮仅在页面上发生某些事情时更新(例如,单击鼠标)。我需要触发变化检测吗?
HTML
<mat-radio-group name="animals" (change)="saveAnimal($event)">
<mat-radio-button *ngFor="let option of animalOptions"
[checked]="option.checked" value="{{option.value}}">{{option.label}}
</mat-radio-button>
</mat-radio-group>
Component.ts
public animalOptions: any = [
{label: 'cat', value: '1', checked: true},
{label: 'dog', value: '2', checked: false}];
然后调用API在ngOnInit中获取数据后:
if (this._choice.animal === 'cat') {
this.animalOptions[0].checked = false;
this.animalOptions[1].checked = true;
}
您共享的用于动态呈现和操作 material 单选按钮组值的代码是正确的。该问题很可能在 how/where this._choice.animal
正在评估中。如果该值是通过 HttpClient
get() 之类的东西检索的,请确保在 subscribe()
或 then()
中评估 this._choice.animal
如果它是 Promise<T>
:
import { Component } from '@angular/core';
@Component({
selector: 'radio-overview-example',
templateUrl: 'radio-overview-example.html',
styleUrls: ['radio-overview-example.css'],
})
export class RadioOverviewExample {
public animalOptions: any = [
{ label: 'cat', value: '1', checked: true },
{ label: 'dog', value: '2', checked: false }
];
public _choice: any;
ngOnInit() {
this.getSomeApiValue().subscribe(result => {
this._choice.animal = result;
if (this._choice.animal === 'cat') {
this.animalOptions[0].checked = false;
this.animalOptions[1].checked = true;
}
});
}
}
这是一个 example 的动作。
希望对您有所帮助!
我有一个带有单选按钮的 Angular Material 应用程序。我想根据数据库中的数据更新所选按钮。一切正常,除了选中的按钮仅在页面上发生某些事情时更新(例如,单击鼠标)。我需要触发变化检测吗?
HTML
<mat-radio-group name="animals" (change)="saveAnimal($event)">
<mat-radio-button *ngFor="let option of animalOptions"
[checked]="option.checked" value="{{option.value}}">{{option.label}}
</mat-radio-button>
</mat-radio-group>
Component.ts
public animalOptions: any = [
{label: 'cat', value: '1', checked: true},
{label: 'dog', value: '2', checked: false}];
然后调用API在ngOnInit中获取数据后:
if (this._choice.animal === 'cat') {
this.animalOptions[0].checked = false;
this.animalOptions[1].checked = true;
}
您共享的用于动态呈现和操作 material 单选按钮组值的代码是正确的。该问题很可能在 how/where this._choice.animal
正在评估中。如果该值是通过 HttpClient
get() 之类的东西检索的,请确保在 subscribe()
或 then()
中评估 this._choice.animal
如果它是 Promise<T>
:
import { Component } from '@angular/core';
@Component({
selector: 'radio-overview-example',
templateUrl: 'radio-overview-example.html',
styleUrls: ['radio-overview-example.css'],
})
export class RadioOverviewExample {
public animalOptions: any = [
{ label: 'cat', value: '1', checked: true },
{ label: 'dog', value: '2', checked: false }
];
public _choice: any;
ngOnInit() {
this.getSomeApiValue().subscribe(result => {
this._choice.animal = result;
if (this._choice.animal === 'cat') {
this.animalOptions[0].checked = false;
this.animalOptions[1].checked = true;
}
});
}
}
这是一个 example 的动作。
希望对您有所帮助!