gpt4 book ai didi

javascript - Angular 2 : How to keep two methods from repeating

转载 作者:行者123 更新时间:2023-12-01 03:52:39 25 4
gpt4 key购买 nike

如何仅实现一次 if/else 语句,以便我不会在 header 组件中重复此代码片段,如下所示:

export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

menuToggle(event: any) {
if (this.navTrigger.nativeElement.classList.contains('opened')) {
this.navTrigger.nativeElement.classList.remove('opened');
} else {
this.navTrigger.nativeElement.classList.add('opened');
}
}

onMenuSelect(event: any) {
this.isMenuShown = false;

if (this.navTrigger.nativeElement.classList.contains('opened')) {
this.navTrigger.nativeElement.classList.remove('opened');
} else {
this.navTrigger.nativeElement.classList.add('opened');
}
}

}

最佳答案

你不应该这样做吗?

export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

menuToggle(event: any) {
if (this.navTrigger.nativeElement.classList.contains('opened')) {
this.navTrigger.nativeElement.classList.remove('opened');
} else {
this.navTrigger.nativeElement.classList.add('opened');
}
}

onMenuSelect(event: any) {
this.isMenuShown = false;

this.menuToggle(event); // Must apply the event binding as well
}

}

关于javascript - Angular 2 : How to keep two methods from repeating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com