标签: angular5

Angular5在数组中插入元素,同时用ngfor显示它

我有一个对象数组(config.lensTab),我在 Html 中使用 ngFor 显示这些对象:

<tr *ngFor="let item of config.lensTab; let i = index;">
          <th scope="row">{{ i + 1}}</th>
          <th><label></label>
          <input [(ngModel)]="item.radius" class="form-control"
                             type="number" step="0.01" name="radius-{{i}}</th>
[...]
Run Code Online (Sandbox Code Playgroud)

我添加了一个“+”按钮,它将在数组中的给定索引(idx)中插入一个元素:

  public addLens(idx: number) {
           let toAdd = new LensModel(0, 0, 0,
           new MaterialModel('Air', 0), 0, 0);
           this.config.lensTab.splice(idx + 1, 0, toAdd);
     }
Run Code Online (Sandbox Code Playgroud)

当我用 console.log 显示数组的内容时,插入操作似乎工作正常。然而,在我的 html 视图中,新行旁边的行与该新行具有相同的值。

我给你一个简单的例子来帮助理解:

Tab : [RED, GREEN, WHITE] --> add "BLUE" at index 1 ---> [RED, BLUE, BLUE, WHITE]
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

编辑:这就是我初始化配置对象的方式

this.config = new ConfigModel(); …
Run Code Online (Sandbox Code Playgroud)

html typescript angular angular5

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

无法绑定到 Directive('appHasAccess'),因为它不是“input”的已知属性

我创建了一个自定义属性指令库包并将其安装到 myProject 中,当我尝试使用此自定义指令时会引发错误。

错误错误:未捕获(承诺):错误:模板解析错误:无法绑定到“appHasAccess”,因为它不是“输入”的已知属性。

我使用的代码如下:

所有可能的尝试我都做了。任何人都知道我如何解决这个问题。

1.指令:HasAccessDirective.ts

@Directive({
  selector: '[appHasAccess]',
})

export class HasAccessDirective {

accessDetail = { 'a': 1 }
 @Input('appHasAccess') set appHasAccess(accessDetail: any) {
    // Based on right control enable/disable
    this.eleRef.nativeElement.disabled = this.appRights.hasRights(accessDetail);
}
constructor(private eleRef: ElementRef,
    private appRights: MyService) { }
}
Run Code Online (Sandbox Code Playgroud)

2.模块:DigiUserRightsModule.ts

   @NgModule({
        declarations: [
            HasAccessDirective
        ],
        imports: [
            CommonModule,
            HttpClientModule,
        ],
        exports: [
            HasAccessDirective
        ],
        providers: [UserRightsService]
    })

export class DigiUserRightsModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: DigiUserRightsModule,
            providers: [UserRightsService]
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

angularjs-directive angular angular-library angular5

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

SwiperJS auto slipsPerView 不适用于 Angular 5

我使用Swiperwith angular 5,但如果我设置slidesPerView: 'auto',幻灯片将无法工作(看不到所有滑块),即使我设置了loopedSlides. 检查生成的CSS代码后,我发现swiper-wrapper是错误的translate3d(1024px, 0px, 0px),并且我看不到滑块。 但如果我调整窗口大小,滑块就会显示! 我可以知道为什么会发生这种情况吗?请帮忙解决这个问题,非常感谢!

源代码:

应用程序组件.ts

import { Component, AfterViewInit } from '@angular/core';
import Swiper from 'swiper';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  silderVm: Swiper;
  ngAfterViewInit(){
    this.silderVm = new Swiper('.swiper-container', {
      loop: true,
      loopedSlides: 2,
      centeredSlides: true,
      spaceBetween: 60,
      slidesPerView: 'auto'
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序组件.html

<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div> …
Run Code Online (Sandbox Code Playgroud)

angular angular5 swiper.js

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

检测 Flux 数据结束与错误

目前正在研究使用 Angular 5 和 Spring 5 webflux 的 SSE。基本应用程序工作正常,但在调查错误处理时,我们注意到,EventSource在角度应用程序中,由于到达 Flux 数据流的末尾而导致弹簧关闭连接与发生错误之间没有任何区别(例如,在传输过程中终止应用程序)。

我们调查所依据的示例如下。

https://thepracticaldeveloper.com/2017/11/04/full-reactive-stack-ii-the-angularjs-client/

http://javasampleapproach.com/reactive-programming/angular-4-spring-webflux-spring-data-reactive-mongodb-example-full-reactive-angular-4-http-client-spring-boot-restapi-server# 25_服务

get中的onerror和completion函数都会在EventSourceSpring成功发送数据并到达流末尾时调用,然后关闭连接,或者当我们ctrl+c应用程序中流时,或者当我们随机抛出异常时发送数据的中间。

该EventSource论证仅包含{type: 'error'}所有 3 种情况。

eventsource spring-webflux angular5

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

当 canActivate 返回 false 时如何重定向另一个组件?

您好,我正在 Angular 5 中使用路由,并且我有一个使用 canActivate 属性的登录路径

当 canActivate 为 false 时,我可以重定向到另一个路径吗?我不希望用户在登录后看到登录页面。

如果用户登录,这里主服务返回 false

{
    path: 'login',
    component: RegisterLoginComponent,
    canActivate: [MainService]
}
Run Code Online (Sandbox Code Playgroud)

routes angular angular5

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

使用角材料5上传文件

我尝试使用角度材料 5 上传文件(角度 5)。

应用程序组件.html

    <mat-horizontal-stepper [linear]="isLinear" #stepper="matHorizontalStepper">

  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Upload your audio file</ng-template>
      <mat-form-field>
          <input matInput  
          style="display: none" 
          type="file" (change)="onFileSelected($event)" 
          #fileInput name ="file" formControlName="firstCtrl" required>
      <button mat-button (click)="fileInput.click()" >Select File</button>
  </mat-form-field>
  <div>
    <button mat-button matStepperNext>Next</button>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)

应用程序组件.ts

export class AppComponent {
  selectedFile: File=null;
  isLinear = true;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  constructor(private _formBuilder: FormBuilder, private http: HttpClient) {}
  ngOnInit() {
   this.firstFormGroup = this._formBuilder.group({
     firstCtrl: ['', Validators.required]
    });
   this.secondFormGroup = this._formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }
Run Code Online (Sandbox Code Playgroud)

但我收到了这个错误 …

file-upload angular-material angular5

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

点击浏览器后退/前进时角度更新内容

除了问题标题之外,我已经在 Angular 5 中编写了一个实现来实现此目的,但我未能使其工作。

https://stackblitz.com/edit/angular-nhtgbr

这个想法是,每当用户在浏览器中单击后退或前进时,应用程序就能够检测到 url 更改并更新内容(如果它仍在同一组件中)。

import { Component, OnInit } from '@angular/core';
import { Location, PopStateEvent } from '@angular/common';
import { ActivatedRoute, Event, NavigationEnd, Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  template: 'Read in console'
})
export class DashboardComponent implements OnInit {

  page: number = 1;

  constructor(private router: Router,
    private activatedRoute: ActivatedRoute,
    private location: Location) { }

  ngOnInit() {

    this.detectPopState();

    setTimeout(() => this.goToPage(1), 1000);
    setTimeout(() => this.goToPage(2), 2000);
    setTimeout(() => this.goToPage(3), 3000);
    setTimeout(() => this.goToPage(4), 4000);
    setTimeout(() …
Run Code Online (Sandbox Code Playgroud)

observable rxjs typescript angular angular5

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

根据角度 5 中的另一个字段值使表单字段成为必填字段

我有以下表格。我想强制使用图表类型。但是,仅当图形是条形图或折线图而不是饼图或圆环图时,才应强制指定 X 轴和 Y 轴值。根据我的代码,X 轴和 Y 轴值始终是强制性的。请帮忙。

html

    <form [formGroup]="clientForm" (ngSubmit)="clientForm.valid && changeGraph()" #formLogin="ngForm">

              <div class="form-group">
            <label> Graph Type </label>
            <select class="form-control" formControlName="type">
              <option disabled [ngValue]="null"> Select Option </option>
              <option *ngFor='let t of types' [ngValue]="t"> {{t}} </option>
            </select>
            <div class="form-err" *ngIf="(clientForm.controls['type'].hasError('required') && clientForm.controls['type'].touched) || (clientForm.controls['type'].hasError('required') && formLogin.submitted)"> Please enter Graph Type </div>
              </div>

              <div class="form-group">
            <label> X-Axis </label>
            <select class="form-control" formControlName="xAxis">
              <option disabled [ngValue]="null"> Select Option </option>
              <option *ngFor='let dim of dimensions?.data' [ngValue]="dim"> {{dim}} </option>
            </select>
            <div class="form-err" *ngIf="(clientForm.controls['xAxis'].hasError('required') …
Run Code Online (Sandbox Code Playgroud)

forms angular5

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

角度形式验证“min”不起作用

我正在阅读https://angular.io/guide/forms。

我的代码:

  <!-- Min price -->
  <div class="form-group">
    <label for="minprice">Min price</label>
    <input type="number"
           min="0"
           class="form-control" id="minprice"
           required
           [(ngModel)]="model.minprice" name="minprice"
           #minprice="ngModel">
    <div [hidden]="minprice.valid"
         class="alert alert-danger">
      Min price is required
    </div>
  </div>

  <!-- Max price -->
  <div class="form-group">
    <label for="maxprice">Min price</label>
    <input type="number" class="form-control" id="maxprice"
           required
           min="0"
           [(ngModel)]="model.maxprice" name="maxprice"
           #maxprice="ngModel">
    <div [hidden]="maxprice.valid"
         class="alert alert-danger">
      Max price is required
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

1、min="0"好像不行。当我输入时-1,没有显示错误消息。

2、如何验证minprice小于maxprice?

欢迎任何提示。谢谢

angular angular-forms angular5 angular6

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

Angular 5 SelectControlValueAccessor 实现错误

我想在 Angular 5 中创建一个自定义选择输入控件。我有一个实现 SelectControlValueAccessor 的组件。当我实现如下所示的课程时。它在代码注释中给出了错误。

import { Component, Input, forwardRef, SimpleChanges, OnChanges } from '@angular/core';
import {  SelectControlValueAccessor } from '@angular/forms';
import { SELECT_VALUE_ACCESSOR } from '@angular/forms/src/directives/select_control_value_accessor';

@Component({    
    selector: 'select-input',
    template: ` `,
    providers: [
        {   
          provide: SELECT_VALUE_ACCESSOR,
            useExisting: forwardRef(() => SelectInputComponent),
            multi: true
        }
    ]
})

/*
[ts]
Class 'SelectInputComponent' incorrectly implements class 'SelectControlValueAccessor'. Did you mean to extend 'SelectControlValueAccessor' and inherit its members as a subclass?
  Property '_renderer' is missing in type 'SelectInputComponent'.
class SelectInputComponent
*/
export …
Run Code Online (Sandbox Code Playgroud)

form-control angular-components angular angular5

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