如何设置ng格式的动态名称
问题描述:
我有一个ng格式的组件。我想动态地设置ng表单的名称,这样我就可以轻松地访问组件的ng元素值。如何设置ng格式的动态名称
例子:
<form name="formName">
<component name="componentName"></component>
</form>
和组件里面我有
<ng-form name="{{$ctrl.name}}">
// Some inputs with special validation
</ng-form>
但每次我试图在我的部分是不确定的,或只是一个字符串而不是访问$ ctrl.name形式与内部输入。
我用的打字稿:
@Component(app, {
selector: 'component',
templateUrl: 'templateUrl',
bindings: {
value: '=?ngModel',
name: '@',
required: '=?ngRequired',
disabled: '=?ngDisabled',
},
})
console.log(this.name); ///A string, but no a form so I can manipulate it.
答
请尝试以下示例代码
Component.js
angular.module('myApp').component('component', {
bindings: {
name: '@'
},
template:
'<ng-form name={{$ctrl.name}}><input name="txtfirst" value="John"/><input type="button" ng-click="$ctrl.getFormData()"></ng-form>',
controller: function($scope) {
console.log(this.name);
this.getFormData = function(){
console.log($scope[this.name]);
}
}
});
HTML
<component name="frmNameTest"></component>
答
如果你想在表单对象是可用Ø控制器,而不是范围,那么你可以这样做,除了表格声明是
<form name="$ctrl[{{$ctrl.name}}]">
...
</form>
是的,代码工作,但不是我想要的。我获得一个带有表单名称的字符串,我希望表单对象具有一个动态名称,这样我可以在控制器内部进行操作。 –
请检查更新的代码。 “$ scope [this.name]”会给出表单对象。 –
这在窗体上工作,但我想在NG-FORM中使用,我不知道如何正确使用。 –