私は角度2のインターフェイスで作業しようとしています。 私はインターフェイスとコンポーネントを作成しました。角2のインターフェイス
インタフェース:
export interface Items {
id: number;
title: string;
message: string;
done: boolean;
}
コンポーネント:
export class AddComponent implements OnInit {
currentItem: string;
todos: any;
constructor(private router: Router) {
this.currentItem = (localStorage.getItem('currentItem')!==null) ? JSON.parse(localStorage.getItem('currentItem')) : [ ];
this.todos = this.currentItem;
}
addTodo(item: Items) {
this.todos.push({
id: item.id,
title: item.title,
message: item.message,
done: false
});
item.title = '';
item.message = '';
localStorage.setItem('currentItem', JSON.stringify(this.todos));
console.log('retorno: ' + this.todos.title + ' titulo: ' + item.title);
this.router.navigate(['./list']);
}
ngOnInit() {}
}
HTML:
<div class="container">
<form (submit)="addTodo()">
<div class="form-group">
<label>Id:</label>
<input [(ngModel)]="id" class="textfield form-control" name="id">
</div>
<div class="form-group">
<label>Titulo:</label>
<input [(ngModel)]="title" class="textfield form-control" name="title">
</div>
<div class="form-group">
<label>Mensagem:</label>
<input [(ngModel)]="message" class="textfield form-control" name="message">
</div>
<button type="submit" class="btn btn-success">Salvar</button>
</form>
</div>
私がエラーを持っている:EXCEPTION: Cannot read property 'id' of undefined
は、それを解決する方法を誰もが知っていますか?
ありがとうございました!それは、この方法でそれをやって、私はインターフェイスを必要としません –
本当に、このようにインターフェイスを必要としません。あなたのコンポーネントにフィールドを直接置くのではなく、データを格納するためにインターフェイス/オブジェクトを使用するのはもうちょっと面倒かもしれません。しかし、どちらの方法ももちろん動作します。 –
ありがとう!今はインターフェイスを使ってそれをやろうとします。 –