【问题标题】:Angular2 / Ionic2: Failed to execute 'setAttribute' on 'Element': '()' is not a valid attribute name.Angular2 / Ionic2:无法在“元素”上执行“setAttribute”:“()”不是有效的属性名称。
【发布时间】:2016-12-23 10:33:43
【问题描述】:

我有一个问题,无论我如何表达,我都不会让我的自定义组件接受我发送的参数。

我尝试了不同的方法,例如使用 {{}}、'' 或不使用 "",但最终如果编译到模板点,我会得到相同的 错误

无法对“元素”执行“setAttribute”:“()”不是有效的属性名称。


我倾向于使用 ionic-cli (2.1.17) 捆绑的最新版本:

  • 角度:2.2.1
  • 离子:2.0.0 - rc.4
  • 打字稿:2.0.9
  • rxjs:5.0.0 - beta.12

基本类是 substitute-helper.ts:

    export class SubstituteHelper {
        number: number;
        kind: string;
    }

这被导入到 substitute.ts:

    import {Component, Input} from '@angular/core';
    import {SubstituteHelper} from '../../app/substitute-helper';

     @Component({
        selector: 'substitute',
        templateUrl: 'substitute.html'
     })
     export class SubstituteComponent {
        @Input()
        sub: SubstituteHelper;
     }

然后在 application.ts 中使用它:

    import {Component} from '@angular/core';
    import {NavController, NavParams} from 'ionic-angular';
    import {OverviewPage} from "../overview/overview";
    import {SubstituteHelper} from '../../app/substitute-helper';

    @Component({
        selector: 'page-application',
        templateUrl: 'application.html'
    })
    export class ApplicationPage {
        showSubstituteVar: boolean = false;
        subs: Array<SubstituteHelper>;
        subNo: number = 0;

        constructor(public navCtrl: NavController, public navParams: NavParams) {}

        addSubstitute(kind: string) {
            var sub = new SubstituteHelper();
            sub.number = this.subNo;
            sub.kind = kind;
            this.subs.push(sub);
            this.subNo += 1;
        }

HTML-template 文件中,我尝试使用它但失败了:

    <div *ngIf="subs.length>0">
        <div *ngFor="let substi of subs">
            <substitute [sub]="substi"></substitute>
        </div>
    </div>

【问题讨论】:

  • 您是否在 application.ts 中导入了“SubstituteComponent”?
  • addSubstitute 是在哪里调用的?什么时候设置潜艇?
  • 你能添加为plunker吗
  • 作为一个小的代码审查,您应该在传递数据时始终使用接口而不是类。类有一个构造函数,一个原型还有一堆你不需要的东西。一个接口可以表示一个简单的 {} 对象
  • 这可能不适用于这种情况,但与类似的错误消息有关:如果离开开始标签的结尾 >,可能会收到奇怪的错误消息。我收到的这样一条错误消息是“元素”:“--”不是有效的属性名称。

标签: angular ionic2 angular2-components


【解决方案1】:

只是通过阅读代码和那里显示的内容来猜测。我发现了两个可能的问题:

  • &lt;div *ngIf="subs &amp;&amp; subs.length&gt;0"&gt;(当时subs大概是undefined
  • subs: SubstituteHelper[] = [](初始化值)

【讨论】:

    【解决方案2】:

    如果没有 *ngIf() 我在上面放了一个标签,这就是现在解决这个错误的方法。

        <div *ngFor="let substi of subs">
            <substitute [sub]="substi"></substitute>
        </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 2021-10-09
      • 2015-04-13
      • 2019-01-11
      • 1970-01-01
      相关资源
      最近更新 更多