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

标签 angular typescript

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

例如,发送评论。


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/

相关文章:

angular - 如何创建自定义原理图来构建新的 Angular 项目

javascript - 如何使用 Angular 5 按顺序运行 2 个 for 循环

javascript - 在单个文件中 bundle typescript 输出

javascript - React Router v4 with Redux - dispatch 未通过

angular - ng-bootstrap typeahead : how to handle Observable<Person[]> rather than Observable<string[]>

javascript - 特定条件下的 Angular2 表单验证

Angular 2未使用的标签错误

angular - 按键事件在 ionic 2 Android 中不起作用

javascript - 将二维数组打印到 HTML 表格

mysql - TypeScript - mysql - socket.io 在尝试登录失败后重新发出