Ошибка при использовании «ElementRef» в экспортируемом компоненте - PullRequest
0 голосов
/ 17 ноября 2018

Я использую ElementRef в CommentComponent, который экспортируется в другие модули, такие как ArticleModule, ProductModule и т. Д. *

// CommentModule
@NgModule({
    exports: [ CommentComponent ],
    declarations: [ CommentComponent ],
    providers: [ CommentService]
})

export class CommentModule { }


// Comment Component (belongs to CommentModule)
@Component({
    selector: 'comments',
    templateUrl: 'comment.component.html',
    styleUrls: ['comment.component.scss']
})
export class CommentComponent implements OnInit {

    suggOnTyping: string = 'hidden';
    constructor(private _eref: ElementRef){}

    @HostListener('document:click', ['$event'])
    onClickOutside(event: any) {
        event.preventDefault();
        event.stopPropagation();
        if (!this._eref.nativeElement.contains(event.target))
            this.suggOnTyping = 'hidden';
    }
}


// Article Module
@NgModule({
    imports: [
        CommonModule,
        RouterModule,
        CommentModule,
        ArticleRoutingModule],
    declarations: [ ArticleComponent ],
    providers: [ArticleService, CommentService, CommentComponent],
    schemas: [ NO_ERRORS_SCHEMA ]
})

ArticleComponent вызывает CommentComponent из вида, подобного этому:

<div class="article">
    .......
    <comments></comments>
</div>

Теперь, когда я пытаюсь маршрутизировать через ArticleComponent, я получаю:

core.js: 1673 Ошибка: Uncaught (в обещании): Ошибка: StaticInjectorError (AppModule) [NgClass -> ElementRef]: StaticInjectorError (Платформа: ядро) [NgClass -> ElementRef]: NullInjectorError: Нет поставщика для ElementRef!Ошибка: StaticInjectorError (AppModule) [NgClass -> ElementRef]: StaticInjectorError (Платформа: core) [NgClass -> ElementRef]: NullInjectorError: Нет поставщика для ElementRef!

Кажется, что ElementRef не может пройти через 'поставщикапотому что, когда я удаляю его из CommentComponent, все работает нормально.

В чем проблема?

Кстати, я использую Angular 6

1 Ответ

0 голосов
/ 17 ноября 2018

Удалить CommentComponent из списка поставщиков AritcleModule.CommentComponent уже объявлено в CommentModule.

// Article Module

@NgModule({
    declarations: [ ArticleComponent], 
    providers: [ArticleService, CommentService, CommentComponent ], //<-- remove from here
    schemas: [ NO_ERRORS_SCHEMA ]
})

Удалите ElementRef из constructor, который вызывает эту ошибку, и если вы хотите получить доступ к элементу, вы можете поместить ссылку на элемент ииспользуйте @ViewChild decorator в файле ts.

Пример:

html

<div #ele>hello/div> <!-- element reference goes here -->

ts

@ViewChild("ele") _eref: ElementRef;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...