Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular/TypeScript中声明键为日期、值为布尔值的对象_Angular_Typescript_Object - Fatal编程技术网

如何在Angular/TypeScript中声明键为日期、值为布尔值的对象

如何在Angular/TypeScript中声明键为日期、值为布尔值的对象,angular,typescript,object,Angular,Typescript,Object,文件app.component.ts,在其类中声明为一个变量,该变量从输入日期开始存储 我希望使用该日期创建一个对象,键为日期,值为布尔值(根据日期的不同,该值为真或假,例如,如果日期在2018年内,则为假,否则为真) Html文件: <input type="date" [(ngModel)]="currentDate"> <button (click)="addDate()">add date</button> 我是Angular的新手,我不知道date

文件
app.component.ts
,在其类中声明为一个变量,该变量从输入日期开始存储

我希望使用该日期创建一个对象,键为日期,值为布尔值(根据日期的不同,该值为真或假,例如,如果日期在2018年内,则为假,否则为真)

Html文件:

<input type="date" [(ngModel)]="currentDate">
<button (click)="addDate()">add date</button>

我是Angular的新手,我不知道
dateObject
应该是什么样子才能存储我想要的东西。有什么建议吗?

您可以创建一个包含所需属性的类。 范例


这就是您需要的吗?

您可以创建一个包含所需属性的类。 范例


这就是你需要的吗?

这就是你可以做的:

export class AppComponent {
    dateArray = [];
    currentDate = "";
    addDate() {
      const currentYear = new Date(this.currentDate).getFullYear();
      if (currentYear === 2018) { 
        this.dateArray.push({
          [this.currentDate]: true
        });
      }

    }
}
您可以将
currentDate
字符串转换为JavaScript日期对象,然后使用该方法获取年份

然后,在将对象推入
日期数组之前,可以继续检查年份是否为2018年


此外,初始化
dateObject
的方式是错误的。对于此场景,您应该使用,例如
{[this.currentDate]:true}

您可以这样做:

export class AppComponent {
    dateArray = [];
    currentDate = "";
    addDate() {
      const currentYear = new Date(this.currentDate).getFullYear();
      if (currentYear === 2018) { 
        this.dateArray.push({
          [this.currentDate]: true
        });
      }

    }
}
您可以将
currentDate
字符串转换为JavaScript日期对象,然后使用该方法获取年份

然后,在将对象推入
日期数组之前,可以继续检查年份是否为2018年


此外,初始化
dateObject
的方式是错误的。对于这种情况,您应该改为使用,例如
{[this.currentDate]:true}

答案的可能重复是使用
{[this.currentDate]:true}
但是您应该在
addDate
内初始化
dateObject
,否则每次只追加相同的对象。答案的可能重复是使用
{[this.currentDate]:true}
但是您应该在
addDate
内初始化
dateObject
,否则每次只能附加相同的对象。
export class AppComponent {
    dateArray: MyCustomClass[] = [];
    currentDate = "";
    newObj: MyCustomClass;
    addDate() {
         newObj = new MyCustomClass(currentDate);
         this.dateArray.push(newObj);
    }
}
export class AppComponent {
    dateArray = [];
    currentDate = "";
    addDate() {
      const currentYear = new Date(this.currentDate).getFullYear();
      if (currentYear === 2018) { 
        this.dateArray.push({
          [this.currentDate]: true
        });
      }

    }
}