如何从子组件更改父变量?

编程入门 行业动态 更新时间:2024-10-25 09:37:01
本文介绍了如何从子组件更改父变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

我在父模板中有一个

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

appponent.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:

appponent.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 './welcomeponent';
import { ShowOffComponent } from './show.offponent';

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

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

show.offfponent.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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 12:32:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   组件   从子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!