与其他组件共享组件数据

时间:2019-07-21 18:37:17

标签: javascript html angular typescript

我一直关注this tutorial,它非常有帮助,但是看来我仍然可以得到它,而且我不明白自己缺少什么!

当鼠标移到子组件(burger-component)中的列表上时,我希望文本动态显示在父组件(header-component)上。

当我徘徊时,它获取文本,发出文本,但是我无法将其发送到父容器!

下面是我的代码:

  • burger-component的列表
    <li><a routerLink="/about" (mouseover)="getText($event)">about</a></li>
          <li><a routerLink="/what-to-expect"(mouseover)="getText($event)">what to expect</a></li>
          <li><a routerLink="/gallery"(mouseover)="getText($event)">gallery</a></li>
          <li><a routerLink="/activities"(mouseover)="getText($event)">activities</a></li>
          <li><a routerLink="/contact"(mouseover)="getText($event)">contact</a></li>
来自汉堡组件的

-ts

  ngOnInit() {
  	this.active = this.init || false;
  } 

  onBurgerClicked() {
    this.active = !this.active;
    this.opened.emit();
  }

  getText(event) {
    this.title = event.target.innerText;
    this.sendTitle.emit(this.title)
    console.log("title sent", this.title);
  }

-ts标头组件

  pageTitle: string;

  constructor() { }

  ngOnInit() {
  }

  getTitle($event) {
    console.log("title recieved");
  	this.pageTitle = $event;
  }

<app-header-component (sendTitle)="getTitle($event)"></app-header-component>

  • 项目中我的文件层次结构的图像 enter image description here

1 个答案:

答案 0 :(得分:2)

您肯定可以通过以下简短的YouTube视频中显示的一些方法来完成此操作:docs

您还应该在这里真正考虑使用字符串插值:

汉堡html

<li><a routerLink="/about" (mouseover)="getText(about)">{{about}}</a></li>
<li><a routerLink="/what-to-expect"(mouseover)="getText(whatToExpect)">{{whatToExpect}}</a></li>
<li><a routerLink="/gallery"(mouseover)="getText(gallery)">{{gallery}}</a></li>
<li><a routerLink="/activities"(mouseover)="getText(activities)">{{activities}}</a></li>
<li><a routerLink="/contact"(mouseover)="getText(contact)">{{contact}}</a></li>

汉堡ts

//Add Output and Event Emitter to your imports
import { Component, OnInit, Output, EventEmitter  } from '@angular/core';

export class BurgerComponent implements OnInit {
  //Add these variables for your string interpolation and also make sure you have the output decorator and variable
  about: string = "About";
  whatToExpect: string = "What to Expect";
  gallery: string = "Gallery";
  activities: string = "Activities";
  contact: string = "Contact";
  @Output() burgerText = new EventEmitter<string>()


  ngOnInit() {
    this.active = this.init || false;
  } 

  onBurgerClicked() {
    this.active = !this.active;
    //this.opened.emit();
  }

  getText(text: string) {
    this.burgerText.emit(text);
    console.log("title sent", text);
  }

}

header html

<h5>{{pageTitle}}</h5>
<app-burger (burgerText)="getTitle($event)"></app-burger>

标题ts

  pageTitle: string;

  constructor() { }

  ngOnInit() {
  }

  getTitle($event) {
    console.log("title recieved: ", $event);
    this.pageTitle = $event;
  }