【问题标题】:Passing data to directive from component将数据从组件传递给指令
【发布时间】:2018-08-08 12:24:36
【问题描述】:

我有以下指令代码:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[while]' })
export class WhileDirective {

constructor(private templateRef: TemplateRef<any>,
            private viewContainer: ViewContainerRef)
{ }

@Input() amountOfTeams: number;
@Input() counter:number;

@Input() set while(condition: boolean) {
        some logic....

    }
}

我的组件

import {Component, OnInit} from "@angular/core";
import {Game} from "../game";
import {PlayGameService} from "../playGame.service";


@Component({
    selector: "teams-Name",
    styleUrls:["teamsName.component.scss"],
    template: `<div  class='start-menu'>
<p  *while="" [amountOfTeams]="" [counter]=""></p>
</div>`

})

export class TeamsNameComponent {

    game: Game;
    counter:number = 0;

    constructor (public playGameService: PlayGameService) {}


    ngOnInit(){
        this.game = this.playGameService.getGame();
        console.log(this.game);
    }

}

我在 app.module.ts 的声明中加载了 WhileDirective

不幸的是,我在编译时遇到了错误:

未捕获的错误:模板解析错误:无法绑定到“amountOfTeams” 因为它不是“p”的已知属性。 (" ][amountOfTeams]="" [counter]="">

"): ng:///e/e.html@1:14 不能绑定到 'counter' 因为它不是一个已知的 'p' 的属性。 (" ][计数器]="">

【问题讨论】:

  • 你能发布这个模块吗?我认为您没有在模块中声明该指令。
  • joxi.ru/BA05YJEIBkW8yr 我做到了

标签: angular input components directive


【解决方案1】:

您收到的错误是因为您尝试绑定到不存在的 p 元素的属性。

要将信息传递到您的结构指令中,请在指令的双引号内输入您的逻辑。

<p *while="some logic"></p>

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2018-10-04
    • 2020-04-01
    • 2020-10-16
    • 2021-10-02
    • 2015-03-30
    • 1970-01-01
    • 2020-07-21
    • 2013-09-27
    相关资源
    最近更新 更多