我正试图创建每年数月的导航。
如果用户是left
月,我想禁用Jan
箭头导航按钮,如果用户是Dec
月,我想禁用右导航按钮。
下面是我的代码
ngOnInit() {
this.year = new Date().getFullYear();
this.monthIndex = new Date().getMonth();
}
要浏览月份
下面是我的代码,
navigationArrowMonth(flag) {
this.monthNavigatorValidation(flag)
}
monthNavigatorValidation(flag?) {
if(flag) {
if(this.monthIndex < 0 || this.monthIndex >= 11) {
this.isRightMonthDisabled = true;
return false;
} else {
this.monthIndex = this.monthIndex + 1;
this.isRightMonthDisabled = false;
return true;
}
} else {
if(this.monthIndex < 0 || this.monthIndex <= 11) {
this.isLeftMonthDisabled = true;
return false;
} else {
this.monthIndex = this.monthIndex - 1;
this.isLeftMonthDisabled = false;
return true;
}
}
}
HTML模板
<!--Month navigation-->
<!--
On click should call navigationArrowMonth
-->
<button [disabled]="isLeftMonthDisabled" (click)="navigationArrowMonth(0)" mat-icon-button id="leftMonthKey" aria-label="left naviage">
<mat-icon>keyboard_arrow_left
</mat-icon>
</button>
<div id="monthValue" class="nameArrage" style="width: 120px;">
<!--
Display month in Alphabets
-->
{{months[monthIndex]}}
</div>
<!--
On click should call navigationArrowMonth
disable when limit reached
-->
<button [disabled]="isRightMonthDisabled" (click)="navigationArrowMonth(1)" mat-icon-button id="rightMonthKey" aria-label="right naviage">
<mat-icon>keyboard_arrow_right
</mat-icon>
</button>
<!--Month navigation end-->
但是我的代码无法正常工作
我在这里做错了什么?
答案 0 :(得分:1)
这个更简单的解决方案
app.component.html
<h2>{{monthIndex}}</h2>
<div>
<button
type="button"
[disabled]="monthIndex <= 0"
(click)="onMove(-1)"
>
LEFT
</button>
<button
type="button"
[disabled]="monthIndex >= 11"
(click)="onMove(1)"
>
RIGHT
</button>
</div>
app.component.ts
year: number;
monthIndex: number;
ngOnInit() {
this.year = new Date().getFullYear();
this.monthIndex = new Date().getMonth();
}
onMove(move: number): void {
this.monthIndex += move;
}
答案 1 :(得分:0)
您是否尝试过删除“?”在 monthNavigatorValidation(flag?)
函数参数之后?在我看来,这应该引发语法错误。
答案 2 :(得分:0)
您没有在每次移动中同时验证两个按钮,并且您的条件存在错误。
要修复代码,请创建一个仅负责导航的功能。
至于验证,可以单独创建一个功能或直接使用* disabled 指令,就像这样:
左月键
[disabled]="monthIndex === 0"
正确的月份键
[disabled]="monthIndex === 11"
答案 3 :(得分:0)
有很多最好的方法,但是由于您正在使用这种逻辑来处理其他问题,因此我修复了您的解决方案,请尝试一下。
monthNavigatorValidation(flag) {
if(flag) {
this.isLeftMonthDisabled = false;
this.monthIndex = this.monthIndex + 1;
if(this.monthIndex === 12) {
this.isRightMonthDisabled = true;
return false;
} else {
return true;
}
} else {
this.isRightMonthDisabled = false;
this.monthIndex = this.monthIndex - 1;
if(this.monthIndex === 1) {
this.isLeftMonthDisabled = true;
return false;
} else {
return true;
}
}
}
答案 4 :(得分:0)
请尝试这样写禁用内容,
[attr.disabled]="monthIndex === 0 ? true : null"
在您的HTML标签中。