首页 > 解决方案 > 与“应用程序模块”通信不起作用

问题描述

我有一个模态弹出窗口。由此我试图与我的父母(应用程序模块)沟通,最后我认为没有办法。但仍然要澄清我发布这个问题。

这是我的应用模板:

 <div class="wrapper" [event]="clickedEvent" >
  <header>
    <app-header #dropDownValue></app-header>
  </header>
  <section>
    <router-outlet></router-outlet>
    <app-category-menu [hideDropDownMenu]="dropDownValue.dropDown" ></app-category-menu>
      <footer>
        <app-footer></app-footer>
      </footer>
  </section>
  <app-cookie-model (eventClicked)="clickedEvent()" ></app-cookie-model>
</div>

应用组件 ts :

import { Component, OnInit, Input } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {

    cookieValue = 'UNKNOWN';

    constructor( private cookieService:CookieService ){}

    ngOnInit():void{
        this.cookieService.set( 'retailAppCookies', 'Hello AppCookie' );
        this.cookieValue = this.cookieService.get('retailAppCookies');
    }

    @Input() clickedEvent(){
        alert('hi'); //not getting any alert
    }

}

我的模态ts:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-cookie-model',
  templateUrl: './cookie-model.component.html',
  styleUrls: ['./cookie-model.component.scss']
})
export class CookieModelComponent implements OnInit {

    cookieAlert:boolean = true;

    @Output() eventClicked = new EventEmitter<Event>(); //not triggering!!

    constructor(private cookieService:CookieService) { }

    ngOnInit() {
        // console.log( this.cookieService.get('retailAppCookies'))
    }

    cookieAgreed(){
        this.eventClicked.emit();
    }

}

得到错误:

Uncaught Error: Template parse errors:
Can't bind to 'event' since it isn't a known property of 'div'. ("<div class="wrapper" [ERROR ->][event]="clickedEvent" >

标签: angularangular5

解决方案


父母可以使用 ViewChild() 与孩子交流,但反之则不行,因为孩子对它的父母一无所知......

但是你有一个输出事件(eventClicked)——你可以从你的父母那里收听它,并在需要时进行一些操作。

您也可以使用服务在这些组件之间进行通信。

最后,如果你想在所有组件之间有一个单一的数据存储,你可以使用 Redux。

但在这里你有一个完全不同的问题。您已经为没有此类输入参数的 div 创建了输入参数 [event]。


推荐阅读