如何根据选择输入操作单个单选按钮



我想根据选择输入将各个单选按钮更改为禁用。

例如,如果用户在选择输入中选择"教学",那么他们已经在"教学"的所有语言都应该在单选按钮中禁用。如果用户选择"学习",那么他们已经在"学习"的所有语言都将被禁用。(所以他们只能挑选新的)

我将收到一份在服务中教授和学习语言的所有语言+用户的列表。现在,我刚刚将它们创建为一个数组。

html

<form [formGroup]="addLanguageFormGroup">
<mat-form-field class="">
<mat-select placeholder="Type" class="full-width" formControlName="type">
<mat-option value="teach">Teach / Native</mat-option>
<mat-option value="learn">Learn</mat-option>
</mat-select>
</mat-form-field>
<br>
<label for="">Select a language</label>
<br>
<br>
<mat-radio-group class="example-radio-group" formControlName="language" aria-label="language">
<mat-radio-button class="example-radio-button" *ngFor="let language of languages" [value]="language"> {{language}}
</mat-radio-button>
</mat-radio-group>
</form>

ts

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
languages:any;
addLanguageFormGroup: FormGroup
teaching: any;
learning: any;
constructor(private formBuilder: FormBuilder,
) { }
ngOnInit() {
this.addLanguageFormGroup = this.formBuilder.group({
type: ['', Validators.required],
language: ['', Validators.required],
});

setTimeout((res) => {
this.languages = ["Language1", "Language2", "Language3", "Language4", "Language5"];
this.teaching = ["Language1"];
this.learning = ["Language3"]
});
}

}

今天再次尝试后,它比我想象的要简单得多。

首先,mat-select有一个更改指令,我们可以获得select输入的值。https://material.angular.io/components/select/api

<mat-select (change)="changed($event)" placeholder="Type" class="full-width" formControlName="type">

在我们得到这个值之后,我们可以将它绑定到一个类型变量,以便稍后在禁用某些单选按钮时使用。

type: any;
changed(v) {
this.type = v.value;
}

然后,我们在mat单选按钮中设置一个禁用指令,指向一个处理禁用单个单选按钮的功能。此功能采用单选按钮的当前语言。

<mat-radio-button class="example-radio-button" *ngFor="let language of languages" [value]="language" [disabled]="isDisabled(language)"> {{language}}
</mat-radio-button>

最后,我们实现isDisabled函数来首先识别类型(学习或教学)。然后,我们检查传递到isDsiabled函数中的当前语言是否在学习语言数组中。如果是,我们返回true以禁用它。我们对教学执行相同的过程。

isDisabled(c) {
if(this.type === "learn")
{
if(this.learning.indexOf(c) > -1) 
{
return true;
}
}
if(this.type === "teach")
{
if(this.teaching.indexOf(c) > -1) 
{
return true;
}
}
return false;
}

查看更新的stackblitzhttps://stackblitz.com/edit/angular-qcr3lv?file=app/app.component.ts

最新更新