gpt4 book ai didi

Angular 在更改时将 ngModel 传递给组件

转载 作者:行者123 更新时间:2023-12-02 19:09:21 25 4
gpt4 key购买 nike

尝试将 ngModel 发送回组件 onchange 以使其显示在控制台上。

Html 文件:尝试借助 log 方法来 console.log ngModel。

<form action="">
<div class="form-group">
<label for="firstname">First name</label>
<input type="text" id="firstName" name="firstName" #firstName = "ngModel"
(change)="log(ngModel)" ngModel
class="form-control"/>
</div>

<div class="form-group">
<label for="comment">Comment</label>
<textarea id="comment" cols="30" rows="10" class="formcontrol"></textarea>
</div>
<button class="btn btn-primary">Submit</button>
</form>

组件

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-form-contact',
templateUrl: './form-contact.component.html',
styleUrls: ['./form-contact.component.css']
})
export class FormContactComponent {

log(x){
console.log(x);
}

}

出现以下错误:

  1. No directive found with exportAs 'ngModel'. (name="firstName" #firstName = "ngModel")
  2. Property 'ngModel' does not exist on type 'FormContactComponent'. ((change)="log(ngModel)"ngModel)

有人可以指导我正确的方向吗?

Similar Question I found in StackOverFlow but that fix does not work. Also i am using the same tutorial mentioned there. I am using Angular 10 currently and the tutorial is angular 4

另外,ngModel在这里是什么意思?我知道 [(ngModel)] 是一种双向绑定(bind)。[ngModel] 将是一个属性,(ngModelChange) 将是事件,它们一起形成 2way 绑定(bind)。独立的 ngModel 代表什么?

最佳答案

使用您的代码,您创建了一个 template-reference-variable 。这意味着 firstName 现在具有指令 ngModel 的属性。

我认为这不是您想要的。也许这样的东西适合你:

<input type="text" name="firstName" (ngModelChange)="log($event)" class="form-control"/>

关于Angular 在更改时将 ngModel 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64553424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com