标签: angular-components

如何在模板中存在ngIf时确定Angular2组件是否已完全加载(包括ViewChilds)

当有条件地加载子项的模板中有ngIf时,是否可以识别Angular2组件(此处为AppComponent)是否已完全加载(包括ViewChilds).

参考:Angular 2 @ViewChild注释返回undefined 此示例取自上面的引用.感谢kenecaswell

import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './child-component-1';
import {SlideshowComponent} from './slideshow/slideshow.component';

@Component({
    selector: 'app',
    template:  `
        <div *ngIf="controlsOn">
            <controls ></controls>
            <slideshow></slideshow>
        </div>
    `,
    directives: [SlideshowComponent, ControlsComponent]
})

export class AppComponent {
    @ViewChild(ControlsComponent) controls:ControlsComponent;   
    @ViewChild(SlideshowComponent) slide:SlideshowComponent;

    controlsOn:boolean = false;

    ngOnInit() {
        console.log('on init', this.controls);
        // this returns undefined
    }

    ngAfterViewInit() {
        console.log('on after view init', this.controls);
        // this returns null
    }

}
Run Code Online (Sandbox Code Playgroud)

由于ngIf条件,在加载子组件之前触发ngOnInit && ngAfterViewInit

我需要在加载SlideshowComponent和ControlsComponent时识别并基于此执行操作.

我有一个hacky解决方案,当有多个ViewChild(不同类型)时不适合 - 使用事件发射器通知子加载的时间.

我发布这个问题,因为经过数小时的研究后没有适当的解决方案.

angular-components angular

7
推荐指数
1
解决办法
2582
查看次数

在Angular 4中对组件应用属性指令

我创建了img-pop组件,它具有@Input()绑定属性src.我创建了authSrc指令,它具有@HostBinding()属性src.

@Component({
selector: 'img-pop',

template: `<img [src]="src"/>
            <div *ngIf="isShow">
                 <----extra value----->
            </div>`
})

export class ImgPopOverComponent implements OnInit {

@Input()
private src;

private isShow=false;

@HostListener('mouseenter') onMouseEnter() {
    this.isShow= true;
}

@HostListener('mouseleave') onMouseLeave() {
    this.isShow= false;
}

}
Run Code Online (Sandbox Code Playgroud)

我有这样的指示.

@Directive({ selector: '[authSrc]' })
export class AuthSrcDirective implements OnInit {

@HostBinding()
private src: string;

constructor(private element: ElementRef) { }

ngOnInit() { }

  @Input()
  set authSrc(src) {
   this.src = src+"?access_token=<-token->";
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望将两种功能结合在一起.

<img-pop [authSrc]="/api/url/to/image"></img-pop>
Run Code Online (Sandbox Code Playgroud)

所以最终的url调用将是/ api/url/to/image?access_token = < …

angular2-directives angular-components angular2-hostbinding angular

7
推荐指数
1
解决办法
6560
查看次数

Angular 2:根据数据加载不同版本的库

我有一个要求,我需要根据数据加载不同的版本模块.

像月度数据这样的东西,如果我当前月份的模块代码发生了一些变化,那么上个月页面的视图/逻辑不应该有任何变化,数据也是如此,因此视图也是如此.

我打算为每个模块创建自定义库.有了这个,我可以用模块版本映射我的数据.

由于我的应用程序很大并涉及如此多的模块和版本,因此我无法将所有版本的模块/库带到客户端.

有人可以提出更好的方法来处理这个要求吗?

angular-components angular2-modules angular angular-library

7
推荐指数
1
解决办法
272
查看次数

Angular 4 - 将对象从一个组件传递到另一个组件(没有父 - 子层次结构)

我的情况:

我有一个组件显示tile,每个tile表示一个数组中的对象,该数组通过ngfor循环.单击一个图块时,我想将该对象传递给另一个组件,该组件负责在可以修改的字段中显示该对象的所有属性.

我尝试过的:

在做了一些研究并发现多个帖子向我展示了如何为父子层次结构实现这一点以及一些帖子解释为了实现想要的功能需要使用共享服务,我决定尝试设置这样的服务.

然而,我似乎没有得到的是当我应该导航到不同的路线.似乎导航在早期找到了位置,因为在详细信息组件中检索它时,传递给服务的对象是未定义的.

我的代码:

显示切片的组件具有以下功能,可将单击的对象传递给共享服务:

editPropertyDetails(property: Property) {
    console.log('Edit property called');

    return new Promise(resolve => {
      this.sharedPropertyService.setPropertyToDisplay(property);
      resolve();
    }).then(
      () => this.router.navigate(['/properties/detail'])
    )
  }
Run Code Online (Sandbox Code Playgroud)

共享服务具有设置属性对象的功能和检索它的功能,如下所示:

@Injectable()
export class SharedPropertyService {
  // Observable
  public propertyToDisplay = new Subject<Property>();

  constructor( private router: Router) {}

  setPropertyToDisplay(property: Property) {
    console.log('setPropertyToDisplay called');
    this.propertyToDisplay.next(property);
  }

  getPropertyToDisplay(): Observable<Property> {
    console.log('getPropertyToDisplay called');
    return this.propertyToDisplay.asObservable();
  }
}
Run Code Online (Sandbox Code Playgroud)

最后是必须接收被单击的对象但获取未定义对象的detail组件:

export class PropertyDetailComponent implements OnDestroy {

  property: Property;
  subscription: Subscription;

  constructor(private sharedPropertyService: SharedPropertyService) {
        this.subscription = this.sharedPropertyService.getPropertyToDisplay()
          .subscribe(
            property …
Run Code Online (Sandbox Code Playgroud)

angular-components angular angular-router

7
推荐指数
1
解决办法
4万
查看次数

如何在 Typescript 中将组件类定义为接口字段?

我有以下界面:

interface Drawer {
  title: string,
  content: Component
}
Run Code Online (Sandbox Code Playgroud)

之后我实例化这个接口:

let workspace: Drawer = {
    title: 'Workspaces',
    content: SidebarWorkspacesComponent
};
Run Code Online (Sandbox Code Playgroud)

在编译期间,我收到以下错误:

ERROR in src/app/components/sidebar/sidebar-toggler.component.ts(36,4): error TS2559: Type 'typeof SidebarWorkspacesComponent' has no properties in common with type 'Component'.
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用 ComponentRef 并阅读了数十篇文章,但无法弄清楚如何在接口中传递组件。显然我可以简单地将内容声明为“任何”,但我宁愿知道如何正确地做事。

提前致谢!

typescript angular-components angular

6
推荐指数
1
解决办法
2818
查看次数

Angular 组件:禁用点击事件

我正在创建一个像这样的可重用组件:

<my-button [isDisabled]="isDisabled" (click)="click($event)"> submit </my-button>
Run Code Online (Sandbox Code Playgroud)

当属性 isDisabled 为 true 时,我想禁用单击事件,我尝试过类似的操作,但它不起作用。

包/组件/my-button.component.html

<button  [disabled]="isDisabled" #myButton>
        <ng-content></ng-content>
</button>
Run Code Online (Sandbox Code Playgroud)

包/组件/my-button.component.ts

@ViewChild('uxButton') uxButton: ElementRef;
@Input() isDisabled: boolean = false;

this.myButton.nativeElement.parentNode.removeEventListener('click' , (e) => {
       e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

angular-components angular

6
推荐指数
4
解决办法
3万
查看次数

在自定义 Angular 组件中访问 FormControl

我正在创建一个自定义角度组件,当我的 FormControl(反应式表单)无效时,它会显示错误工具提示。但我不知道如何访问自定义组件中的 FormControl 以检查它是否被标记为有效。

我想要完成的

<div [formGroup]="form">
     <input formControlName="name" type="text" />
     <custom-validation-message formControlName="name">My special error message!</custom-validation-message>
  </div>
Run Code Online (Sandbox Code Playgroud)

已经遇到的东西

错误错误:没有名称的表单控件的值访问器:'surveyType'

通过使用 NG_VALUE_ACCESSOR 实现 ControlValueAccessor 来修复此问题,即使我不想更改该值。我还添加了一个注入器来访问 NgControl。

import { Component, OnInit, Injector } from '@angular/core';
import { NgControl, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    selector: 'custom-validation-message',
    templateUrl: './validation-message.component.html',
    providers: [{
        provide: NG_VALUE_ACCESSOR, multi: true, useExisting: ValidationMessageComponent
    }]
})
export class ValidationMessageComponent implements ControlValueAccessor, OnInit {
    public formControl: any;

    constructor(private injector: Injector) {
        super();
    }

    public ngOnInit(): void {
        const model = this.injector.get(NgControl); …
Run Code Online (Sandbox Code Playgroud)

angular-components angular angular-reactive-forms

6
推荐指数
1
解决办法
4781
查看次数

将 ng-template 传递给子组件

我创建了一个可重用的组件来呈现表格。它目前适用于基本表格,但在某些情况下我希望能够自定义表格中的单个列/单元格。

这是我在父组件中使用的代码:

<!-- PARENT TEMPLATE -->
<app-table
  [headers]="headers"
  [keys]="keys"
  [rows]="rows">
</app-table>

// PARENT COMPONENT
public headers: string[] = ['First', 'Last', 'Score', 'Date'];
public keys: string[] = ['firstName', 'lastName', 'quizScore', 'quizDate'];
public rows: Quiz[] = [
  { 'John', 'Doe', 0.75, '2020-01-03T18:18:34.549Z' },
  { 'Jane', 'Doe', 0.85, '2020-01-03T18:19:14.893Z' }
];
Run Code Online (Sandbox Code Playgroud)

我在子组件中使用的代码:

<!-- CHILD TEMPLATE -->
<table>
  <thead>
    <tr>
      <td *ngFor="let header of headers">
        {{ header }}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of rows">
      <td *ngFor="let key of keys">
        {{ render(key, …
Run Code Online (Sandbox Code Playgroud)

angular-template angular-components angular

6
推荐指数
1
解决办法
4011
查看次数

Angular Nebular 样式不适用于 NbChatComponent

我有一个正在进行的 angular 项目,我正在尝试将 Nebular Chat UI 添加到该项目中。

我使用 npm 安装了 nebular 并按照网站中的说明进行了导入。功能按预期工作,但样式未应用于组件。

以下是我遵循的步骤。

  1. npm install --save @nebular/theme @angular/cdk @angular/animations
  2. npm install --save @nebular/eva-icons
  3. 在 app.module.ts 中导入 NbThemeModule 和 NbC​​hatModule

    import { NbThemeModule, NbChatModule } from '@nebular/theme';
    
    @NgModule({
    imports: [
      ...
      NbThemeModule.forRoot(),
      NbChatModule
    ]
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在 angular.json 中添加样式

    "styles": [
          "node_modules/@nebular/theme/styles/prebuilt/default.css"
    
    Run Code Online (Sandbox Code Playgroud)
  5. 添加了 html 组件(站点中提供了示例)

    <nb-chat title="Nebular Conversational UI">
        <nb-chat-message *ngFor="let msg of messages"
                         [type]="msg.type"
                         [message]="msg.text"
                         [reply]="msg.reply"
                         [sender]="msg.user.name"
                         [date]="msg.date"
                         [files]="msg.files"
                         [quote]="msg.quote"
                         [latitude]="msg.latitude"
                         [longitude]="msg.longitude"
                         [avatar]="msg.user.avatar">
    </nb-chat-message>
    
    <nb-chat-form (send)="sendMessage($event)" [dropFiles]="true">
    </nb-chat-form>
    
    Run Code Online (Sandbox Code Playgroud)

输出 1

在此处输入图片说明

参考:

https://akveo.github.io/nebular/docs/guides/install-nebular#manually …

styles angular-components styled-components angular nebular

6
推荐指数
1
解决办法
1363
查看次数

如何从 Angular 中的另一个服务调用一个服务的特定实例?

因此,我有一个组件“motions”,它在通过一些用户输入单击按钮后执行MotionService 。然后,该服务需要根据输入将数据传递给 DebateComponent 的特定 CaucusService实例(我们将其称为服务 A)或 DiscussComponent 的 CaucusService 实例 B。
但是,到目前为止,我似乎在 MotionService 中有一个 CaucusService 的新实例。DebateComponent 和 DiscussComponent 需要 CaucusService 的不同实例,因此我在每个 @Component 中提供了它

基本上,我的 MotionService 需要在给定特定用户输入的情况下将数据传递给 A 或 B 我应该如何解决这个问题?

service dependency-injection angular-services angular-components angular

6
推荐指数
2
解决办法
1万
查看次数