Angular:如何对从组件外部导入的变量进行插值?

时间:2019-08-07 01:38:06

标签: angular ecmascript-6

如果从Angular Component外部导入常数值,应如何在模板中插值?

import { MAXIMUM } from '../utils/currency'

@Component({
  selector: 'my-component',
  template: `
    <div>Maximum is ${MAXIMUM}</div>
  `,
  styleUrls: ['./my.component.css']
})
export class MyComponent {

}

4 个答案:

答案 0 :(得分:1)

没有我的朋友你想做这样的事情

import { MAXIMUM } from '../utils/currency'

@Component({...})
export class MyComponent {


 constructor(public maximum:MAXIMUN) { }



}

现在您可以通过这种方式使用.html文件MyComponent.html中的元素

<p>{{maximum}}</p>

如果希望在打字稿文件中声明x变量,我希望您能在示例中找到逻辑。您可以在HTML文件中使用“ {{x}}”使用它

答案 1 :(得分:1)

您应该创建一个类变量,并将其值分配给常量,如下所示:

import { MAXIMUM } from '../utils/currency'

@Component({...})
export class MyComponent {

  Maximum = MAXIMUM;
}

现在像这样在模板中使用此变量:

 <div>Maximum is ${{Maximum}}</div>

希望有帮助。

答案 2 :(得分:1)

.ts

1) include that external file like .js in angular.json or index.html

No need to import

declare const Maximum; //<=====

.html

{{Maximum}}

.ts

import { MAXIMUM } from '../utils/currency'

@Component({
  selector: 'my-component',
  template: '<div>Maximum is {{MAXIMUM}}</div>', // No need of $
  styleUrls: ['./my.component.css']
})
export class MyComponent {

}

答案 3 :(得分:1)

您在template中使用模板文字的语法不正确。您需要使用反引号(``)而不是单引号('')或双引号("")。

只需将代码更改为以下

import { MAXIMUM } from '../utils/currency';

@Component({
  selector: 'my-component',
  template: `<div>Maximum is ${MAXIMUM}</div>`,
  styleUrls: ['./my.component.css']
})

export class MyComponent { }

以下是StackBlitz上的一个示例。

当然,如果您要使用templateUrl,那么这是不可能的,您必须在组件中将MAXIMUM分配给变量(例如currencyMax),您可以使用角度插值{{currencyMax}}(来源:docs)将其绑定到HTML。第二种方法也是标准方法,因为我们更喜欢使用Angular插值法将我们的值绑定到模板而不是模板字符串。

import { MAXIMUM } from '../utils/currency';

@Component({
  selector: 'my-component',
  template: '<div>Maximum is {{currencyMax}}</div>',
  styleUrls: ['./my.component.css']
})

export class MyComponent {
  public currencyMax: number = MAXIMUM;
}

或使用单独的HTML文件作为模板。

my.component.html

<div>Maximum is {{currencyMax}}</div>

my.component.ts

import { MAXIMUM } from '../utils/currency';

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

export class MyComponent {
  public currencyMax: number = MAXIMUM;
}