角度:将属性传递到动态组件模板

时间:2018-07-25 16:11:06

标签: javascript angular attributes components accordion

我创建了一个组件,并且我想通过该组件将属性传递给模板。 这是组件:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-card-generator',
  templateUrl: './card-generator.component.html',
  styleUrls: ['./card-generator.component.css'],
  inputs: ['id', 'collapseid', 'headingid','collapsehashid']
  })
export class CardGeneratorComponent implements OnInit {
  bindings: {
            headingid:'@?',
    collapseid:'@?',
    collapsehashid
           }
  constructor() { }
  ngOnInit() {}

这是模板:

<button class="btn btn-link collapsed"  style="text-decoration:none;" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          {{id}}
        </button>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body"></div>
    </div>

通过以下方式将创建的组件放置在home.component中:

<div id="cardDivContainer" >

    <app-card-generator id="Chart 1" collapsehashid="data-target='#collapseOne'" collapseid="aria-controls='collapseOne'" headingid="aria-labelledby='headingOne'"></app-card-generator>
    <app-card-generator id="Chart 2" collapsehashid="data-target='#collapseTwo'" collapseid="aria-controls='collapseTwo'" headingid="aria-labelledby='headingTwo'"></app-card-generator>

  </div>

我只需要为每个组件设置“数据目标”,“ aria-labelledby”和“ aria-controls”属性(取决于组件ID)。

我是Angular的新手,我希望以上所述是有道理的。

1 个答案:

答案 0 :(得分:2)

您可以使用validationInfo.push({ value: { elementId: "txtsearchBar", validateFunc: isEmpty }, index: 'step1'}); 引用组件中的元素。元素可以作为参数传递到外部。像这样:

@Input

如果您所引用的元素中不存在属性,则可以使用import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-card-generator', styleUrls: ['./card-generator.component.css'], templateUrl: './card-generator.component.html' }) export class CardGeneratorComponent implements OnInit { @Input() id: string; @Input() collapseid: string; @Input() headingid: string; @Input() collapsehashid: string; constructor() { } ngOnInit() {} } 并使用attr.attribute表示法

{{}}

最后,您可以在外部调用中访问在组件中创建的属性

<button class="btn btn-link collapsed"  style="text-decoration:none;" type="button" data-toggle="collapse" attr.data-target="{{'#' + collapseid}}" aria-expanded="false" attr.aria-controls="collapseid">

        </button>
    <div id="{{collapseid}}" class="collapse" attr.aria-labelledby="{{headingid}}" data-parent="#accordionExample">
      <div class="card-body"></div>
    </div>

此链接中的更多<div id="cardDivContainer" > <app-card-generator id="Chart 1" collapsehashid="collapseOne" headingid="headingOne"></app-card-generator> <app-card-generator id="Chart 2" collapsehashid="collapseTwo" headingid="headingTwo"></app-card-generator> </div> @Input详细信息:

https://stackblitz.com/edit/card-generator-sample?file=src%2Fapp%2Fapp.component.html