如何从子组件更改父变量? [英] How to change parent variable from children component?

查看:34
本文介绍了如何从子组件更改父变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题很简单,但我无法摆脱它.

This question is quite simple but I can't get rid of it.

我在父模板中有一个

并且在通过路由模块显示子模板时需要它消失.我期望的是在标题标签中添加一个类,以便我可以通过 CSS 隐藏它.这就是我所拥有的:

app.component.ts

I have a <header> in parent template and I need it disappear when displaying children template through routing module. What I expect is adding a class to the header tag so I can hide it via CSS. This is what I have:

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app',
  template: `
    <header [class.hidden]="hide">
      <h1>My App</h1>
      <ul>
            <li><a href="/home"></a></li>
            <li><a href="/showoff"></a></li>
      </ul>
    </header>
    <router-outlet></router-outlet>
  `
})

export class AppComponent {
  hide = false; // <-- This is what I need to change in child component
}

app-routing.module.ts

import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './welcome.component';
import { ShowOffComponent } from './show.off.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'showoff', component: ShowOffComponent },
];

export const AppRouting = RouterModule.forRoot(routes, {
  useHash: true
});

show.offf.component.ts

import { Component } from '@angular/core';
@Component({
   selector: 'app-showoff',
   template: `
       <h2>Show Off</h2>
       <div>Some contents...</div>
   `
})

export class ShowOffComponent {
   hide = true; // <-- Here is the problem.
                // I don't have any idea how to reach parent variables.
}

推荐答案

您可以使用 输出发射器

在您的子组件中,

import { Component } from '@angular/core';
@Component({
   selector: 'app-showoff',
   template: `
       <h2>Show Off</h2>
       <div>Some contents...</div>
   `
})

export class ShowOffComponent {
    @Output() onHide = new EventEmitter<boolean>();
    setHide(){
       this.onHide.emit(true);
    }
}

在父级中,

export class AppComponent {
  hide = false;

  changeHide(val: boolean) {
    this.hide = val;
  }
}

使用该事件发射器将子项添加到父项,

Add a child to the parent with that event emitter,

<app-showoff (onHide)="changeHide($event)"></app-showoff>

这篇关于如何从子组件更改父变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆