从循环打字稿中选择按钮

时间:2019-01-26 18:17:46

标签: typescript angular6

enter image description here我有很多人在循环播放,很难为我解释我想要这样的东西

<div *ngFor="let person of persons">
{{person.name}} {{person.surname}}
<button class="btn {{mmm}}" (click)="chosePerson(person.id)">chose</button>

每个用户都有自己的按钮,当我单击按钮时,它应该完全更改该按钮的颜色

在我的person.component.ts

persons: IPersons[];
mmm: any = 'btn-success';

chosePerson(id: number) {
    this.persons.forEach(element => {
        if (element.id === id) {
            element.clicked = true;
            this.mmm = 'btn-danger';
        } else {
            element.clicked = false;
            this.mmm = 'btn-success';
        }
    });
}

在我的person.model.ts

export interface IPerson{
id?: number;
name?: string;
surname?: string;
age?: number;
self_number?: string;
parent_number?: string;
home_number?: string;
photoContentType?: string;
photo?: any;
clicked?: boolean;}

export class Person implements IPerson{
constructor(
    public id?: number,
    public name?: string,
    public surname?: string,
    public age?: number,
    public self_number?: string,
    public parent_number?: string,
    public home_number?: string,
    public photoContentType?: string,
    public photo?: any
) {}}

1 个答案:

答案 0 :(得分:0)

向每个人员对象添加一个额外的字段。为其命名,例如clicked

,然后在HTML中使用ngClass伪指令。仅当此特定人的clicked设置为true时,才会添加其他类。

<div *ngFor="let person of persons">
    {{person.name}} {{person.surname}}
<button class="btn" [ngClass]="{'mmm': person.clicked==true}" 
    (click)="chosePerson(person.id)">chose</button>

然后在您的TS文件中遍历列表,并将clicked-field设置为true。同时将所有其他参数都设置为false;

chosePerson(id: number) {
    this.persons.forEach(element => {
        if (element.id === id) {
            element.clicked = true;
        } else {
            element.clicked = false;
        }
    });
}

这应该可以解决问题。