angular - 表示组件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>
似乎还不错,但我遇到了问题,在哪里写两个逻辑案例:
- 仅设置一个徽章处于活动状态
- 将任何徽章设置为活动状态
所以,我不想要在父组件中设置徽章的逻辑<app-sidebar>
。我想将它封装在 itdelf 中。
我没有信心,可能是我的组件结构错误,因此我有问题。
解决方案
当有多个应用程序徽章实例并且您需要特定状态时。然后最好放置一个变量来包含这样的状态:
@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;
}
}
这给出了一个属性来设置值,如果需要的话,可以做一些事情,比如改变一个类等。
推荐阅读
- python-3.x - 我如何从 sqlite 中删除一个元组,以便我可以将它用作 python 中的浮点数?
- python - “import xxx”不能在 jupyter notebook 上工作,但在命令提示符下工作
- c++ - 如何从亮度中计算像素的 RGB 值?
- javascript - Flask - 可以在子程序期间请求最新的上下文吗?
- java - 映射定义不能嵌套在类型 [_doc] 下,除非 include_type_name 设置为 true
- reactjs - 如何在 ReactJS 中将对象值传递给子级
- google-apps-script - 使用脚本在 Google 表格中动态隐藏一行
- c# - 运行程序时未创建应用程序用户?
- react-native - 如何在 react native 中创建精确大小的 UI 组件?
- sql - 有没有更好的方法来优化这个 SQL 查询?