我想知道如何使用 textarea 在 Angular 中建模

fly*_*igh 3 typescript angular

我想使用模型并发送到服务器。

例如,发送评论。


评论.model.ts

export interface Comment {
  article_no: number;
  username: string;
  nickname: string;
  creatat: Date;
  content: string;
}
Run Code Online (Sandbox Code Playgroud)


评论.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);
  }
}
Run Code Online (Sandbox Code Playgroud)


comment.component.html (我使用材质 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>
Run Code Online (Sandbox Code Playgroud)

我用过 [formControl],但我想知道是否有更好的方法。


评论.component.ts

...
export class CommentComponent implements DoCheck {
  content = new FormControl();
}
...
addComment() {
    this.commentService.writeComment(this.content.value);
}
Run Code Online (Sandbox Code Playgroud)

我想将“this.content.value”放在“comment.model.ts中的内容”中,并通过comment.service.ts将其传递给服务器。


如果您有更好的方法,我将不胜感激。

谢谢你。

Fai*_*sal 6

由于它是一种形式,因此 aformControl对用户来说很好。如果需要,您也可以使用[(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>
Run Code Online (Sandbox Code Playgroud)

和打字稿将如下所示:

...
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);
}
Run Code Online (Sandbox Code Playgroud)