通过路由器出口的角度6子对父交互

问题描述 投票:0回答:3

我有带有两个子组件的应用程序组件,分别是第一个和第二个,我正在浏览路由器出口标签。当我单击子组件按钮时,我想将父组件变量更改为“ XYZ”。

app.component.html

<a routerLink = "/first">
  First
</a>
<a routerLink = "/second">
  Second
</a>
<div>
  <router-outlet></router-outlet>
</div>
{{myvar}}

app.component.ts

export class AppComponent {
  title = 'childParentInteraction';
  myvar : String = "ABCD";
}

app-routing.module.ts

const routes: Routes = [
  {
    path:"first", component: FirstComponent
  },
  {
    path:"second",component: SecondComponent
  }
];

first.component.html

<div>
    <p>first works!</p>
    <button (click)="changeVar()">
        Change variable
    </button>
</div>

first.component.ts

export class FirstComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  changeVar(){
  }
}
angular angular-components angular-component-router
3个回答
0
投票

关于这个故事:

您应该创建一个保存变量的服务。

my-var.service.ts

@Injectable({providedIn: 'root'})
export class MyVarService {
  private myVar$ = new BehaviorSubject<any>(null);
  myVar: Observable<any> = this.myVar$.asObservable();

  setMyVar(newValue: any) {
    this.myVar$.next(newValue);
  }
}

FirstComponent:您需要注入并使用服务的setMyVar方法。

fist.component.ts

export class FirstComponent {

  constructor(private myVarService: MyVarService) {}

  setValue(value: any) {
    this.myVarService.setMyVar(value);
  }
}

AppComponent:您需要听观察myVar的声音

app.component.ts

export class AppComponent implements OnInit, OnDestroy {

  myVar: any;
  destroyer$: Subject<void> = new Subject();

  constructor(private myVarService: MyVarService) {}

  ngOnInit() {
    this.myVarService.myVar.pipe(takeUntil(this.destroyer$)).subscribe(myVar => this.myVar = myVar);
  }

  ngOnDestroy() {
    this.destroyer$.next();
    this.destroyer$.complete();
  }
}

0
投票

欢迎使用堆栈溢出!

您可以在Angular 6中使用一个技巧:

通过在子组件上注入ViewContainerRef:

constructor(private viewContainerRef: ViewContainerRef) { }

而且您可以像这样访问:

getParentComponent() {
  return this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ 
   '_view' ].component
  }

  this.getParentComponent().myvar = "XYZ"

0
投票

您可能想要一个eventEmitter:

<router-outlet (messageEvent)="buttonClicked($event)"></router-outlet>

然后在子ts文件中:

将Output和EventEmitter添加到您的导入语句。添加一个@Output语句然后添加this.messageEvent.emit('pressed');

© www.soinside.com 2019 - 2024. All rights reserved.