我在 Angular 表单中的输入没有显示它的默认值

My input inside a form in Angular is not showing it's default value

我有一个表单,我想在其中一个输入中有一个默认值,该默认值是用户的显示名称,但是,它没有显示,甚至添加时也没有显示“hi”作为输入的默认值,我不确定我应该做什么:

<form [formGroup]= "postForm" (ngSubmit)="onSubmit()" novalidate>
  <div class="mb-3">
    <label>Title</label>
    <input type="text" formControlName="title" class="form-control" required>
  </div>

  <div class="mb-3">
    <label>Content</label>
    <input type="text" formControlName="message" class="form-control" required>
  </div>

  <div class="mb-3" *ngIf="authService.userData as user" >
    <input type="text" value="{{user.displayName}}" formControlName="owner" class="form-control">
  </div>

  <div class="mb-3">
    <button type="submit" class="btn btn-primary" [disabled]="!postForm.valid">Create</button>
  </div>


</form>

这是与之相关的打字稿组件:

    import { Component, OnInit } from '@angular/core';
import {AuthService} from "../shared/services/auth.service";
import { PostService } from '../post.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from "@angular/router";



@Component({
  selector: 'app-create-post',
  templateUrl: './create-post.component.html',
  styleUrls: ['./create-post.component.scss']
})
export class CreatePostComponent implements OnInit {
  public postForm: FormGroup;

  constructor(public postService: PostService,
              public formBuilder: FormBuilder,
              public router: Router,public authService: AuthService){
    this.postForm = this.formBuilder.group({
      title: [''],
      message: [''],
      owner: [''] ,
      date: new Date().toLocaleString()
    })
  }

  ngOnInit(): void {
  }

  onSubmit() {
    this.postService.createPost(this.postForm.value);
    this.router.navigate(['list-posts']);
  };

}

非常需要和感谢帮助,我还想指出,我曾尝试将 diplayname 值直接放入 TypeScript 文件中,但它不存在,只能从 html 文件中获得.

您不应该将 value 与 Angular 受控形式一起使用,相反,初始值是您在打字稿文件中提供的值,因此,请从 html,并将打字稿文件 owner: [''] , 替换为 owner: this.authService.userData 甚至 owner: 'hi' 以确保其有效。