How can I get reference of child component and emit a value from child component

℡╲_俬逩灬. 提交于 2019-12-11 15:07:29

问题


I have a parent component ValidateSessionComponentwhich has a child component LoginFormComponent. In my unit test, I want to emit a value from LoginFormComponent but I am unable to figure out how I can do so.

The HTML of the ValidateSessionComponent has reference of the LoginFormComponent.

<app-login-form #loginForm (formOutputEvent)="handleFormValues($event)" [userId]="username"></app-login-form>

The LoginFormComponent looks like

export class LoginFormComponent implements OnInit {

  loginForm:FormGroup;

  formData:LoginFormValues;
  @Input() userId;
  @Output() formOutputEvent: EventEmitter<LoginFormValues>;
  existingUser:UserSigninInfo;

..
}

In the test, i want to emit formOutputEvent by calling formOutputEvent.emit(formData); But I can't figure out how to access formOutputEvent of LoginFormComponent in ValidateSessionComponent's spec.

  fit('should send signin request on receiving form values ',(done)=>{
    //let loginComponent:LoginFormComponent = TestBed.get(LoginFormComponent); //IF I UNCOMMENT THIS THEN I GET ERROR NO PROVIDER OF LOGINFORMCOMPONENT
    let userService:UserManagementService = TestBed.get(UserManagementService);
    component.loginForm.formOutputEvent.emit(new LoginFormValues('test@test.com','somepassword'));

    spyOn(userService,'signinUser');
    setTimeout(()=>{
      expect(userService.signinUser).toHaveBeenCalledWith(new UserSigninInfo('test@test.com','somepassword'));
      done();
    },1000);

  });

I thought I could use the ViewChild directive @ViewChild(loginForm) loginFormRef; but I suppose I'll get an ElementRef. I can't figure out how to access the formOutputEvent.

来源:https://stackoverflow.com/questions/58263959/how-can-i-get-reference-of-child-component-and-emit-a-value-from-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!