简体   繁体   English

如何在Angular选择器中传递变量

[英]How to pass variables in an Angular selector

I have an angular charComponent that creates pie, and line and other graphs which I want to embed in various places in my app. 我有一个可创建饼图,折线图和其他图形的有角charComponent,我想将它们嵌入到应用程序的各个位置。

I use the selector: 我使用选择器:

<chart></chart>

To expose a chart. 公开图表。

What I want to do is embed a variable into the code so I can tell the component what chart I want returning. 我想做的是在代码中嵌入一个变量,这样我就可以告诉组件我要返回什么图表。

So something like this: 所以像这样:

<chart variable="pie-chart"></chart>

Is something like this possible or is there a better way to do it? 这样的事情可能吗,还是有更好的方法呢?

It is called property binding and is one of the core concepts you should/will be using with Angular. 这称为属性绑定,它是您应该/将要与Angular一起使用的核心概念之一。

  1. Define the variable, which will be passed to your ChartComponent as 定义变量,该变量将作为

     export class ChartComponent { @Input() public varName: string; // this is typed as string, but you can use any type you want constructor() {} } 
  2. Now you can use 现在您可以使用

<chart [varName]="varValue"></chart>

OR 要么

<chart varName="varValue"></chart>

to pass the variable value to the ChartComponent. 将变量值传递给ChartComponent。 The difference between the two notations is that with the first one you pass the varValue, which will be evaluated; 两种表示法的区别在于,第一种表示法传递的是varValue,它将被求值; whereas in the second notation the varName value IS 'varValue'. 而在第二种表示法中,varName值为IS'varValue'。

And yes, the Angular docs are sometimes quite good. 是的,Angular文档有时还不错。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM