【发布时间】:2018-04-03 22:18:46
【问题描述】:
我正在尝试制作一个可重用的组件,该组件基本上在单击时从一个图标切换到另一个图标。我尝试过使用和不使用 ng-template、使用 *ngIf 和使用 switch case。
根据评论编辑
这是我的例子:
图标切换组件
@Component({
selector: 'app-icon-toggle',
template: `
<a [ngClass]="iconStyle" [ngSwitch]="active">
<i *ngSwitchCase="true" class="fa {{activeIcon}}"></i>
<i *ngSwitchCase="false" class="fa {{inactiveIcon}}"></i>
</a>
`
})
export class IconToggleComponent implements AfterContentChecked {
@Input() active: boolean;
@Input() activeIcon: string;
@Input() inactiveIcon: string;
@Input() iconStyle: string;
ngAfterContentChecked(): void {
console.log('content check', this.active);
}
}
使用它的组件
@Component({
selector: 'app-admin-info-toggle',
template: `
<template #loading><i></i></template>
<div style="display: flex; flex-direction: row; align-items: start;">
<app-icon-toggle [active]="showChangeInfo"
[activeIcon]="'fa-eye'"
[inactiveIcon]="'fa-eye-slash'"
[iconStyle]="'show-change-info'"
(click)="toggleShowChangeInfo()">
</app-icon-toggle>
<!-- ORIGINAL SETUP THAT I AM EXTRACTING -->
<div *ngIf="lockEditing; then editIcon else lockIcon"></div>
<ng-template #editIcon>
<a class="change-lock" (click)="toggleEdit()">
<i class="fa fa-edit"></i>
</a>
</ng-template>
<ng-template #lockIcon>
<a class="change-lock" (click)="toggleEdit()">
<i class="fa fa-lock"></i>
</a>
</ng-template>
</div>
`
})
export class AdminInfoToggleComponent implements OnInit {
lockEditing = true;
showChangeInfo = true;
constructor(private sessionService: SessionService) {}
ngOnInit(): void {
this.sessionService.getLockEditing()
.subscribe(isLocked => this.lockEditing = isLocked);
}
toggleEdit() {
this.sessionService.toggleEditingLock(this.lockEditing)
.subscribe(isLocked => this.lockEditing = isLocked);
}
toggleShowChangeInfo() {
this.showChangeInfo = !this.showChangeInfo;
}
}
会话服务
@Injectable()
export class SessionService implements OnInit {
lockEditing = new Subject<boolean>();
ngOnInit(): void {
this.lockEditing.next(true);
}
getLockEditing() {
return this.lockEditing;
}
toggleEditingLock(isLocked: boolean) {
this.lockEditing.next(!isLocked);
this.lockEditing.subscribe(isLocked =>
console.log('toggleEditingLock [result]', isLocked));
return this.lockEditing;
}
}
我想它需要更多细节,因为它只是代码。
【问题讨论】:
标签: angular toggle angular5 angular-ng-if