【问题标题】:How can i change the attribute from other component in angular如何更改角度中其他组件的属性
【发布时间】:2018-12-04 11:16:32
【问题描述】:

我有两个组件:

注册并登录。

在 RegisterComponent 我有锚点:

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

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

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

我尝试输入属性,但我用来显示这个组件,我不能使用&lt;app-logincomponent [already-client]="true"&gt;

我该怎么做?

谢谢

【问题讨论】:

  • 使用 EventEmitters、Subjects 和 Observables。看看这个:stackoverflow.com/questions/51380223/…
  • 我尝试: public handleSubscriptions() { this.subscription = this.registrarService.setCliente_JControle.subscribe( action => { console.log(action); } ) } 在服务中: setCliente_JControle(possui_conta: boolean ) { this.cliente_jcontrole.next({action: true}); } 但我得到:[ts] 属性 'subscribe' 在类型 '(possui_conta: boolean) => void' 上不存在。

标签: angular typescript


【解决方案1】:

在这里,将组件导入到您要更改值的父组件...假设子组件,将子组件导入父组件:

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;
}

【讨论】:

    【解决方案2】:

    如果您在注册组件中使用了登录组件,那么使用@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 "> 
    

    【讨论】:

      【解决方案3】:

      什么对我有用:

      登录:

      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});
        }
      

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多