简体   繁体   English

更改后的angular4测试输入值

[英]angular4 testing input values after change

I would to change value of my input while testing so I did: 我会在测试时更改输入值,所以我做了:

const de = fixture.debugElement.query(By.css('[formControlName="username"]'));
de.nativeElement.value = "10";

Then I submit the form: 然后我提交表格:

component.onSubmit();

And the value of the input still is unchanged. 并且输入的值仍保持不变。 I tried to add 我试图添加

fixture.detectChanges();

After submit the form, but it actually does nothing. 提交表单后,但实际上不执行任何操作。

Why are you getting the element by the CSS selector? 为什么通过CSS选择器获取元素? Angular has a way to create Reactive Forms which are MUCH easier than what you're trying to do. Angular有一种方法来创建反应式表单 ,这比您尝试做的要容易得多。 Take this example: 举个例子:

export class ReactiveFormExampleComponent implements OnInit {
  public form: FormGroup;

  constructor () { } 

  ngOnInit(): void {
    this.form = new FormGroup({ 
      'username': FormControl(null, [/** Any form validators here **/]) 
    });
  }

  onSubmit(): void {
    // get the value of the username
    const username = this.form.get('username').value;
  }
}

If you really wanted to watch the value and detect the changes without pressing a button with an attached click event you would do this after initializing the form. 如果您确实希望观看该值并检测到更改而无需按下带有附加click事件的按钮,则可以在初始化表单后执行此操作。

this.form.get('username').valueChanges.subscribe(val => {
  // new username value is `val`
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM