【问题标题】:Angular 2-Cannot import another component in component declarationAngular 2-无法在组件声明中导入另一个组件
【发布时间】:2017-02-26 12:32:04
【问题描述】:

我是 Angular 2 的新手,目前正在试验它,这是我遇到的问题

喜欢组件代码

like.component.ts

import { Component ,Input} from '@angular/core';

@Component({
  selector: 'like',
  template: `
  <span (click) ="onClick()" class="glyphicon glyphicon-heart" [class.liked]="isLike" ></span>
  <span>{{likeCount+incrmentCOunt}}</span>

  `,
  styles:[`
        .glyphicon-heart{
          color:#ccc;
        }

        .liked{
          color:deeppink;
        }
  `]

})
export class LikeComponent  { 
  @Input("like") isLike = false;
  @Input() likeCount:number;
  incrmentCOunt=0;
  onClick(){
   if(this.isLike){
     this.isLike=false;
this.incrmentCOunt=0;
   }else{
     this.isLike=true;
     this.incrmentCOunt=1;
        }
  }

}

在实现嵌套组件时,我将所有组件导入到 ngModule 装饰器中,并将其添加为这样的声明

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TweetComponent } from './tweet/tweet.component';
import { AppComponent }  from './app.component';
import { LikeComponent } from './like/like.component';
@NgModule({
    imports:      [ BrowserModule ],
    declarations: [ AppComponent ,TweetComponent,LikeComponent],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

这工作得很好,现在我决定从 ngModule 中删除 LikeComponent 并尝试将其导入 TweetComponent,

tweet.component.ts

import { Component,Input } from '@angular/core';
import { LikeComponent } from './../like/like.component';

@Component({
  selector: 'tweet',
  template: `
  <div class="media">
  <div class="media-left">
    <a href="#">
      <img class="media-object" [src]="tweet.img" alt="...">
    </a>
  </div>
  <div class="media-body">
    <h4 class="media-heading">{{tweet.name}} <span>{{tweet.handle}}</span></h4>
    <div >{{tweet.content}}</div>
    <div>
    <like [likeCount]="tweet.likeCount"></like>
    </div>
  </div>
</div>
  `   
  ,
  declarations:[LikeComponent]
})
export class TweetComponent  { 
    @Input() tweet={
            name:"Mukul",
            handle:"@mukul",
            content:"some content",
            likeCount:20
        }

}

这里我无法使用它,我试图将它注入 decleration 并且由于指令都不起作用,类型相关的错误显示在崇高

希望在这里得到一些澄清,谢谢

【问题讨论】:

  • LikeComponent 代码更新您的帖子。首先,您要实现什么目标?
  • 确定@Aravind 现在更新了,我正在尝试在推文组件中导入likeComponent,LikeComponent 最初是在应用程序模块中导入的,但我想看看它是否可以在推文组件中导入,或者不能
  • 删除声明:[LikeComponent] 。你需要在你的模块中清除 thr 组件
  • @YoavSchniederman 在模块中声明 LikeComponent 工作正常,只是想看看是否可以在另一个组件定义中导入和声明一个组件。所以结论是所有组件都必须在一个ngModule中导入和声明?

标签: javascript angularjs angular typescript


【解决方案1】:
declarations:[LikeComponent]

@Component() 中,自 2.0.0-RC.6 起已消失

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 2017-01-17
    • 1970-01-01
    • 2017-07-07
    • 2018-05-31
    • 2018-05-31
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多