Angular2 Pass属性值从html模板动态地动态为@input

时间:2016-05-26 09:49:52

标签: angular angular2-template angular2-directives

如何在[email]属性中传递动态值而不是字符串?

我遇到了Parse语法错误。我是否可以通过ngFor动态地将值传递给@input装饰器,并使用角度表达式动态传递 [email] 属性,例如 {{member.email}} 帮助我在html上使用这种语法。

注意:像[email] =“'XXX@XX.com'这样的静态输入可以很好地提取数据

EXCEPTION: Template parse errors:
Parser Error: Missing expected : at column 8 in [{{member.email}}] in AppComponent@56:49 ("class="avatar" *ngFor="let member of teamMembers">
   <li><a href=""><gravatar-image [size]="80" [ERROR ->][email]="{{member.email}}"></gravatar-image></a></li>
            </ul>
            </div>
"): AppComponent@56:49

HTML模板代码:

<div class="row">
    <div class="col-md-12">
        <h4>Team Members</h4>
        <ul class="avatar" *ngFor="let member of teamMembers">
        <li><a href=""><gravatar-image [size]="80" 
          [email]={{member.email}}></gravatar-image></a></li> //Here i get error 
                               I am not able to assign input value dynamically by 
                               getting "member.email" value through expression. 

        </ul>
        </div>
        </div>

指令组件输入:

@Component({
selector: 'gravatar-image',
template: '<img [src]="getGravatarImage()">',
styles: ['img{width: 40px;height: 40px;margin: 10px;overflow: hidden;float: left;display: inline-block;border-radius: 100%;}']
})
export class GravatarImageComponent {
@Input() size:number = 80;
@Input() email:string = "";

getGravatarImage():string {
    return 'http://www.gravatar.com/avatar/' + md5(this.email) + '?s=' + this.size;
}
}

应用组件:

import { Component, OnInit, Input } from 'angular2/core';
import { Observable }     from 'rxjs/Rx';
import { Location, LocationStrategy } from 'angular2/platform/common';
import { GravatarImageComponent } from './gravatar-image.component';
import { UserService } from './user.service';
import { User } from './user';

@Component({
  selector: 'editor',
  templateUrl:'../template/XXX.html',
  providers: [UserService],
  directives: [GravatarImageComponent]
})
export class AppComponent implements OnInit {
  teamMembers: User[];
  .....etc

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:4)

您不需要使用双花括号,只需使用引号。

<gravatar-image size="80" [email]="member.email"></gravatar-image>

答案 1 :(得分:1)

这最终对我有用

.navbar-default{
       background-color:#000000
}

没有 <gravatar-image [size]="80" [email]=member.email>