Angular 输入的 ngModel 和 Value 不能一起工作

Angular input's ngModel and Value don't work together

我对 angular 中的表格有疑问。我的目标是制作一个表格,其中填充了可以更改的默认值。验证表单后,它会将数据发送到 MySQL 数据库。

这是component.html代码:

<form #adopt="ngForm" (ngSubmit)="success()">
        <label for="email">Email:</label>
        <input type="email" name="email" [(ngModel)]="adoptions.email" #email="ngModel">
        <label for="animal">Twój wybór to:</label>
        <input type="text" name="animal" [(ngModel)]="adoptions.animal" #email="ngModel">
        <button [disabled]="adopt.form.invalid" type="submit">Adoptuj</button>
        <button (click)="getAnimal('')" class="disable">Odznacz swój wybór</button>
      </form>

这是 typeScript 代码:

export class AdoptpageComponent implements OnInit {

adoptions = new Adoptions();
sessionValue
animal
value
msg='';

constructor(private userService: UserService, private shared: SharedService, private _service 
: AdoptService, private _router : Router) {
}

ngOnInit(): void {
  this.getUsers();
  this.sessionValue = sessionStorage.getItem('email');
}

getAnimal(arg) {
  this.animal = arg;
}

success() {
  this._service.create(this.adoptions).subscribe(
    data => {
      console.log("dziala");
      this._router.navigate(['/adopt'])
    },
    error => {
      console.log("nie dziala");
      this.msg = error.error;
    }
  )
}

}

我在上面发布的代码有效,但只有当我从键盘将值输入到表单中时才有效。我希望第一种形式自动检索 sessionValue 的值,第二种形式自动检索动物。当我输入而不是 ngModel 时,我设法实现了它:

<input type="email" name="email" [value]="sessionValue" #email="ngModel">

但是随后表单不起作用(它不向数据库发送数据)。不幸的是,当两者都使用时,[value] = "sessionValue" 不起作用

<input type="email" name="email" [value]="sessionValue" [(ngModel)]="adoptions.email" #email="ngModel">

您知道如何使用默认值提交表单吗?

首先:您将 adoptions.emailadoptions.animal 绑定到 ngModel,但它们是空的(或者更糟 - nullundefinedngOnInit 被解雇,这就是您的输入为空的原因。一旦您在输入中引入文本,它们就会有价值,这就是为什么您能够成功执行 this._service.create

其次:您造成了值绑定冲突。 ngModel 的来源与 value 的来源不同。一旦 ngOnInit 被触发,value 尝试在输入中加载 sessionValue 的值,而 ngModel 尝试不加载任何内容,因为它的源是空的

如果你有 ngModel,就不需要使用 value。您只需为其源变量设置起点值。像下面的例子

ngOnInit(): void {
   adoptions.email = somehowGetEmail()
   adoptions.animal= somehowGetAnimal()
}

如果您坚持使用 ngModels,这就是您要做的全部。

但总的来说,这看起来像很多不必要的绑定。由于这些是 form inputs,您应该使用 form's preimplemented features for value bindings。检查 angular FormBuilder, formControl

的文档