我该如何从Angle中的其他组件更改属性

时间:2018-12-04 11:16:33

标签: angular typescript

我有两个组成部分:

注册并登录。

在RegisterComponent中,我具有锚点:

<a id="titleClient">Already have a account? Click here</a>

当用户单击此锚点时,我需要将Login属性has_client设置为true:

export class LoginComponentimplements OnInit {
  already_client: boolean
  ...
}

我尝试输入属性,但我用来显示此组件,无法使用<app-logincomponent [already-client]="true">

我该怎么办?

谢谢

3 个答案:

答案 0 :(得分:0)

在这里,将组件导入到您要更改其值的父组件中。假设孩子,将孩子导入到父组件中

parentComponent.ts

import { Component, OnInit, OnDestroy, ViewChild } from "@angular/core";
import { myChildComponent } from "./myChildComponent";

//inject child component to use its own functions.
@ViewChild(myChildComponent) childComponent: myChildComponent;

changeChild(){
this.childComponent.setAuthorization(true);
}

之后,您可以在子组件内部使用功能。

在myChildComponent.ts

//You will reach this function from your Parent component...
setAuthorization(state: boolean){
 this.myAuthState = state;
}

答案 1 :(得分:0)

如果在注册组件中使用了登录组件,那么使用@Input装饰器将非常简单。

ts

import Input from "@angular/core";

export class LoginComponent implements OnInit {

  @Input("user-client")
  already_client: boolean
  ...
}

html

<a id="titleClient" (click)="alreadyClient = true">Already have a account? Click here</a>
<app-logincomponent [already-client]="alreadyClient "> 

答案 2 :(得分:0)

对我有用的东西

登录:

ngOnInit() {
    this.handleSubscriptions()
  }

  public handleSubscriptions() {
    this.subscription = this.registrarService.params.subscribe(
      action => {
        if(action !== undefined){
          this.usuario.client= action.action
        }
      }
    )
  }

注册

  setPossui(){
    this.registrarService.setParameters(true);
    this.router.navigate(['/login']);
  }

服务:

private client: BehaviorSubject<any> = new BehaviorSubject<any>({} as any);
  public params = this.cliente.asObservable().pipe(distinctUntilChanged());

  public setParameters(possui_conta: boolean) {
    this.client.next({action: possui_conta});
  }