我正在努力讓@Directive按預期工作。Angular2屬性指令表格輸入
我希望Attr指令能夠訪問指令構造函數中的model.password並將變量varpassword設置爲當前密碼。
我還希望能夠檢索表單域中的所有其他輸入,我將如何去做這件事?
很多這樣的文檔並不完整,因爲我在Beta版本中知道。
我一直在試圖找出有限的成功天。我已經刪除了我試圖讓它工作的導入,因爲我覺得我很困惑如何在指令中正確使用它們,我試過「NgModel,NgControl,ControlGroup,NgFormModel,FormBuilder ...」。
我的測試示例代碼如下。
登錄-form.html
<form #testForm="ngForm">
Email Address:
<input type="text" name="username" size="50" required="required" [(ngModel)]="model.username" ngControl="username" #username="ngForm" />
Password:
<input type="password" name="password" size="20" required="required" [(ngModel)]="model.password" ngControl="password" #password="ngForm" testdir />
<input type="submit" value="Login" />
</form>
app.ts
import {Component} from 'angular2/core';
import {TestDirective} from '../../directives/test.directive';
@Component({
selector: 'test-app',
templateUrl: 'login-form.html',
directives: [TestDirective]
})
export class TestApp {}
test.directive.ts
import {Directive} from 'angular2/core';
@Directive({
selector: '[testdir]',
host: {
'(keydown)': 'run()'
}
})
export class TestDirective {
varpassword: string;
constructor() {
this.varpassword = [******]
}
run() {
console.log(this.varpassword);
}
}
如果任何人都可以在正確的方向指向我會更讚賞。
謝謝你完美。我試圖在我的測試中設置構造函數中的變量,難怪爲什麼它不起作用。 我現在已經工作如何使用控制檯(this.form.controls)時也訪問ngForm;我可以看到它返回的對象,你知道一種方法來檢查輸入類型,例如密碼,輸入等嗎? 再次感謝。 –
您需要利用組件的生命週期掛鉤。在構造函數中爲時尚早...要訪問輸入類型,需要注入'ElementRef'。你可以通過'nativeElement.type'來獲得這個提示。我更新了plunkr ;-) –
好吧,我看到這是爲attr指令輸入,但表單對象內的所有其他輸入是什麼。 我想要實現的是觀察表單中的所有輸入以更改爲ngModel,表單可以包含任何數量的輸入,因此不僅僅是用戶名和密碼。 例如名稱,地址1,地址2,郵編,電子郵件,用戶名,密碼,驗證密碼。我將循環遍歷ngForm.controls對象和任何不是輸入密碼的輸入,我會將其推入指令中的新數組中,並在自定義密碼驗證程序中使用它們的值。 感謝您的幫助:) –