标签: angular8

如何将 EventEmitter 与动态组件结合?

我正在尝试结合动态组件(在运行时创建)和 EventEmitter 概念来访问 Angular 8 中父组件中子组件的数据。

我的计划是创建一个功能,用户可以在其中动态添加元素(例如仪表板上的卡片)并删除它们。在这种情况下,创建的卡片有一个“删除”按钮。这个删除按钮应该将信息传播到父组件,子组件可以从包含动态创建的组件的数组中删除。

我在本教程中从 angular 文档中了解到,我需要创建一个指令。现在我有了断言(我认为),该指令位于父组件和子组件之间,我不知道如何正确发出事件以从提到的数组中删除子组件。


指令

@Directive({
  selector: '[appCards]'
})
export class CardDirective {

  constructor(public viewContainerRef: ViewContainerRef) {
  }

  @Output() directiveDelete = new EventEmitter<any>();
}
Run Code Online (Sandbox Code Playgroud)

父组件

card-banner.component.ts

@Component({
  selector: 'app-card-banner',
  templateUrl: './card-banner.component.html',
  styleUrls: ['./card-banner.component.scss']
})
export class CardBannerComponent implements OnInit, OnDestroy  {

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  @Input() cards: CardItem[];

  @ViewChild(CardDirective) appCards: CardDirective;

  loadCards() {
    const viewContainerRef = this.appCards.viewContainerRef;
    viewContainerRef.clear();
    for (const card of this.cards) {
      const componentFactory =
        this.componentFactoryResolver.resolveComponentFactory(card.component);
      const componentRef = …
Run Code Online (Sandbox Code Playgroud)

angular-directive angular angular-event-emitter angular8

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

Angular8 : ng run =&gt; '项目目标不存在。' 使用 i18n 时

基于这些教程:https : //angular-templates.io/tutorials/about/angular-internationalization-i18n-multi-language-apphttps://medium.com/@ismaestro/angular-7-example-app- with-angularcli-angular-universal-i18n-official-firebase-66deac2dc31e 我正在尝试使用 i18n 作为国际化系统构建和使用 Angular 8 应用程序。

但是,当我尝试运行时npm build:ssr(参见下文),我得到An unhandled exception occurred: Project target does not exist.

在这里,angular.json:

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "newProjectRoot": "projects",
    "projects": {
        "boilerplate": {
            "root": "",
            "sourceRoot": "src",
            "projectType": "application",
            "architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                        "outputPath": "dist",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        "tsConfig": "tsconfig.app.json",
                        "polyfills": "src/polyfills.ts",
                        "assets": [
                            "src/assets",
                            "src/favicon.ico"
                        ],
                        "styles": [
                            "src/styles.scss"
                        ],
                        "scripts": []
                    },
                    "configurations": {
                        "en": {
                            "outputPath": "dist/browser/", …
Run Code Online (Sandbox Code Playgroud)

angular-i18n angular angular8

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

如何使用angular 2+中的click事件动态创建按钮

我想动态创建一个按钮。我使用innerHtml 来做到这一点。我可以创建按钮。但它的点击事件不起作用。请告诉我如何解决这个问题?

这是我的 html 代码

<div  [innerHTML]="answerPanelContent"></div>
Run Code Online (Sandbox Code Playgroud)

这是我的打字稿代码

 answerPanelContent: any;

   constructor(private sanitizer: DomSanitizer){

   }
ngOnInit() {
 this.answerPanelContent =  this.sanitizer.bypassSecurityTrustHtml(`<button type="button" class="btn                                                    btn-primary float-left"
                                           (click)="removeAnswer()" title="Remove Answer"
                                           aria-label="Close">
                                          Remove</button>`);

  }
    removeAnswer(){
      alert('clicked');
    }
Run Code Online (Sandbox Code Playgroud)

这是 stackblitz 网址:https ://stackblitz.com/edit/angular-nka4w9

typescript angular angular8

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

在 Angular 8 中,如何在单击提交按钮时将所有值转换为 JSON?

我想通过单击提交按钮将带有键和值的表单数据推送为 JSON 格式。

我不想手动创建 JSON。请帮我解决这个问题。

angular-reactive-forms angular8

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

为 Angular 8 测试设置顺序

我的一项测试随机失败。我想设置一些调试顺序,因为默认情况下测试使用种子随机运行。我试图在karma.conf.js或设置种子数,random: false但没有效果。我使用默认测试配置并使用ng test. 我的变化karma.conf.js

client: {
   ...
   random: false,
   //or
   seed: '71384' 
   ...
}
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular angular-test angular8

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

如何使用卡片而不是 angular 8 中的数据表过滤数据?

我正在尝试使用卡片过滤数据,但我没有设法使用卡片而不是数据表过滤它

例子:在此处输入图片说明

import { Component, OnInit } from '@angular/core';
import {MatTableDataSource} from '@angular/material/table';

@Component({
  selector: 'app-publicaciones',
  templateUrl: './publicaciones.component.html',
  styleUrls: ['./publicaciones.component.css']
})
export class PublicacionesComponent implements OnInit {
  private users = ['Fabio', 'Leonardo', 'Thomas', 'Gabriele', 'Fabrizio', 'John', 'Luis', 'Kate', 'Max'];
  
  dataSource = new MatTableDataSource(this.users);
  constructor() { }

  ngOnInit() {
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

}
Run Code Online (Sandbox Code Playgroud)
.container {
    max-width: 900px;
    justify-items: center;
    justify-content: center;
    text-align: center;
    margin: auto;
    max-width: 80%;
    padding-left: 80px;
    padding-top: 8%;
}

.example-card {
    padding-left: 105px; …
Run Code Online (Sandbox Code Playgroud)

css angular angular-material-6 angular8

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

使用 ngIf 单击外部指令?

如果单击位于具体 DOM 元素之外,我使用以下指令来检测和隐藏块:

import {
  Directive,
  ElementRef,
  Output,
  EventEmitter,
  HostListener
} from "@angular/core";

@Directive({
  selector: "[clickOutside]"
})
export class ClickOutsideDirective {
  constructor(private _elementRef: ElementRef) {}

  @Output()
  public clickOutside = new EventEmitter();

  @HostListener("document:click", ["$event.target"])
  public onClick(targetElement) {
    const clickedInside = this._elementRef.nativeElement.contains(
      targetElement
    );

    this.clickOutside.emit(clickedInside);
  }
}
Run Code Online (Sandbox Code Playgroud)

我已将此指令应用于元素:

<div class="action" (click)="open()">Open</div>
<div
    class="search_content"
    *ngIf="_searchContentOpen"
    clickOutside
    (clickOutside)="clickOutside($event)"
  ></div>
Run Code Online (Sandbox Code Playgroud)

组件代码为:

open(): void {
   this._searchContentOpen = !this._searchContentOpen;
}
Run Code Online (Sandbox Code Playgroud)

问题是当我调用 click 我设置this._searchContentOpen为真/假。

取决于它,我会显示应用指令的块。但是当 ngIf 工作时,指令也总是同步工作。因此,永远不会显示结果块。

如何解决?

angular angular5 angular8

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

无法加载角度生成的网页(ng build --prod)

使用“ ng build --prod ”部署我的 angular 应用程序后,我尝试打开 index.html 文件并检查我的 web 应用程序。但它在 chrome、firefox 和边缘网络浏览器中不显示任何内容。打开控制台并检查是否有任何错误后,它将显示 6 条错误消息。

我的网络应用程序中的 6 个错误

我应该提到我的应用程序成功编译并在http://localhost:4200/ ”上运行。在我尝试了另一个角度应用程序(新的)之后,但它在构建后出现了同样的错误。

错误:

1) 从源 'null' 访问 'file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/runtime-es2015.edb2fcf2778e7bf1d426.js' 的脚本已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

2) GET file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/runtime-es2015.edb2fcf2778e7bf1d426.js net::ERR_FAILED

3) 从源“null”访问“file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/polyfills-es2015.2987770fde9daa1d8a2e.js”的脚本已被 CORS 政策阻止:仅跨源请求支持协议方案:http、data、chrome、chrome-extension、https。index.html:36

4) GET file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/polyfills-es2015.2987770fde9daa1d8a2e.js net::ERR_FAILED index.html:1

5)从源“null”访问“file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/main-es2015.69da1b25d5a7a648b825.js”的脚本已被CORS政策阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。index.html:36

6) GET file:///D:/AngularTshirt/module01/moduleapp01/dist/moduleapp01/main-es2015.69da1b25d5a7a648b825.js net::ERR_FAILED

google-chrome webdeploy angular angular8

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

在 Angular 8 中等待 Service Api 调用完成

我正在尝试我的第一个 Angular 8 Crud Web 应用程序并编写了一个页面来列出来自 WebApi 的一些公司名称

我的服务正确获取数据并且我能够在控制台上打印它

//Service.ts
export class CompanyService {
  allCompanys: Company[]
  constructor(private httpClient: HttpClient) { }
  // Returns all the companys
  GetAll(): Company[] {

    this.httpClient.get<Company[]>('https://localhost:565656/api/company').subscribe(result => {
      this.allCompanys = result;

      //Shows data Sucessfully from Server :Working fine
      console.log(this.allCompanys);

    }, error => console.error(error));

    return this.allCompanys;
  }
Run Code Online (Sandbox Code Playgroud)

但是在我的组件中,我尝试通过调用服务来获取页面开头的数据并将其分配给本地变量,它给出了未定义

     ///Component.ts

      export class CompanyListComponent implements OnInit {
      Companylist: Company[] 
 constructor(private route: ActivatedRoute, private router: Router, private companyService: CompanyService) {  }
        ngOnInit() {

          this.Companylist = this.companyService.GetAll();  
          //This is executing before …
Run Code Online (Sandbox Code Playgroud)

rxjs angular angular8

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

Ionic 4、Angular 8 和 HTTP 拦截器

我正在使用 Ionic 4 和 Angular 8 构建移动应用程序,但无法使我的 HTTP 拦截器正常工作。我在这里查看了拦截器的所有示例,但没有一个适合我的需要,或者根本不再起作用。

与常规 Angular 8 版本的唯一区别是从存储中读取令牌的第一行。原始的 Angular 8 代码同步读取这些东西并且不需要订阅因此它可以工作。这里是 Ionic 存储,它以异步方式调用本地资源。

这是我的代码:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  from(this.storage.get('id_token')).subscribe(res => {
    const idToken = res;
    if (idToken) {
      const cloned = req.clone({ headers: req.headers.set('token', idToken)});
      return next.handle(cloned);
    } else {
      console.log('Unauthorized calls are redirected to login page');
      return next.handle(req).pipe(
        tap(
          event => {
            // logging the http response to browser's console in case of a success
            if (event instanceof HttpResponse) {
              // console.log('api …
Run Code Online (Sandbox Code Playgroud)

ionic4 angular8

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