首页 > 解决方案 > 表示组件Angular的逻辑?

问题描述

有一个自定义组件app-badge,它创建了彩色徽章和自定义文本:

@Component({
    selector: 'app-badge',
    templateUrl: './badge.component.html',
    styleUrls: ['./badge.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BadgeComponent implements OnInit {
    @Input() badge: Badge;
    @Input() cssClass: string;
    @Output() onSelect = new EventEmitter<Badge>();
    public isSelected: boolean;

    constructor() {}

    ngOnInit() {}

    public select() {
        this.onSelect.emit(this.badge);
        this.isSelected = !this.isSelected;
    }
}

模板是:

<span (click)="select()" class="badge p-2 mb-1 mr-2" [ngClass]="{ 'primary-color-dark': isSelected, 'badge-unchecked': !isSelected }">{{
    badge.label
}}</span>

我在另一个内部使用这个组件<app-sidebar>

<app-badge
    *ngFor="let pagesize of paginationService.getPageSizeOptions()"
    [badge]="{ label: pagesize, value: pagesize }"
    [cssClass]="'primary'"
    (onSelect)="setPageSize($event)"
></app-badge>

似乎还不错,但我遇到了问题,在哪里写两个逻辑案例:

  1. 仅设置一个徽章处于活动状态
  2. 将任何徽章设置为活动状态

所以,我不想要在父组件中设置徽章的逻辑<app-sidebar>。我想将它封装在 itdelf 中。

我没有信心,可能是我的组件结构错误,因此我有问题。

标签: angular

解决方案


当有多个应用程序徽章实例并且您需要特定状态时。然后最好放置一个变量来包含这样的状态:

@Component({
    selector: 'app-badge',
    templateUrl: './badge.component.html',
    styleUrls: ['./badge.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BadgeComponent implements OnInit {
    @Input() badge: Badge;
    @Input() cssClass: string;
    @Output() onSelect = new EventEmitter<Badge>();
    public isSelected: boolean;
    active:false;

    constructor() {}

    ngOnInit() {}
    public onSetActiveProperty(value){
       this.active=value;
       // now do something with the newly set value
    }
    public select() {
        this.onSelect.emit(this.badge);
        this.isSelected = !this.isSelected;
    }
}

这给出了一个属性来设置值,如果需要的话,可以做一些事情,比如改变一个类等。


推荐阅读