我想使用模型并发送到服务器。
例如,发送评论。
comment.model.ts
export interface Comment {
article_no: number;
username: string;
nickname: string;
creatat: Date;
content: string;
}
comment.service.ts
import { Injectable } from '@angular/core';
import { ApiService } from '.';
import { Observable } from 'rxjs/Observable';
import { Comment } from '..';
@Injectable()
export class CommentService {
constructor(
private apiService: ApiService
) { }
public writeComment(comment: Comment) {
return this.apiService.post('/api/comment/', comment);
}
}
comment.component.html
(我用的是material UI)
<form class="comment-form">
<mat-form-field class="example-full-width">
<textarea matInput matTextareaAutosize [formControl]="content" placeholder="comment"></textarea>
</mat-form-field>
<button class="ui primary button" (click)="addComment()"> Add </button>
<button class="comment-btn">Save</button>
</form>
我用过[formControl],但我想知道是否有更好的方法。
comment.component.ts
...
export class CommentComponent implements DoCheck {
content = new FormControl();
}
...
addComment() {
this.commentService.writeComment(this.content.value);
}
我想把 'this.content.value' 放在 'content in comment.model.ts' 中,然后通过 comment.service.ts 将它传递给服务器。
如果您有更好的方法,我将不胜感激。
谢谢。
最佳答案
因为它是一个表单,所以 formControl
对用户来说很好。如果需要,您还可以使用 [(ngModel)]
。将您的模板更改为以下内容:
<form class="comment-form">
<mat-form-field class="example-full-width">
<textarea matInput matTextareaAutosize [(ngModel)]="content" placeholder="comment">
</textarea>
</mat-form-field>
<button class="ui primary button" (click)="addComment()"> Add </button>
<button class="comment-btn">Save</button>
</form>
typescript 看起来像这样:
...
export class CommentComponent implements DoCheck {
content: string;
}
...
addComment() {
let comment: Comment = { content: this.content,
// You can initialize/set other properties as well
};
this.commentService.writeComment(comment);
}
关于angular - 我想知道如何使用 textarea 在 Angular 中建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839033/