I have a table Component where when the user Selects a particular row he is Redirected to a different route to a team component .
I want to Load the View Of the New Route when all the data from the Service has been Fetched by the Component .
How to Prevent the View From rendering till the Time the whole data has been fetched from Service in the New components OnInit Method.
in angular 1 there was ngCloak how to do it in Angular 2 .
I have used ngIf but for a split second till the data loads the div pops up and then disappears
My table Component
onSubmit(team:any){
this.teamId = team._links.team.href.split('/').pop(-1);
this.competitionService.storeTeamCrest(team.crestURI);
this.router.navigate(['team', {id: this.teamId}]);
}
Service
storeTeamCrest(link:string){
this.teamCrest = link;
}
getPlayers(id:string){
let headers = new Headers();
headers.append('X-Auth-Token', 'XXX');
return this.http.get('https://api.football-data.org/v1/teams/'+id+'/players',{headers:headers}).map(response => response.json())
}
getFixtures(id:string){
let headers = new Headers();
headers.append('X-Auth-Token', '7c94f28bddf34648bd9a6f5c2e2da0f0');
return this.http.get('https://api.football-data.org/v1/teams/'+id+'/fixtures',{headers:headers}).map(response => response.json())
}
Team Component
ngOnInit(){
this.teamId = this.route.snapshot.params['id'];
this.teamCrest = this.competitionService.teamCrest;
this.getPlayers();
}
getPlayers(){
this.competitionService.getPlayers(this.teamId).subscribe(player => this.players = player.players);
}
Team Component Template
<div class="container">
<div class="row">
<div *ngFor="let player of players"#data>
<div class="col-md-4">
<div class="well box">
<img class="avatar" src="{{teamCrest}}">
<h4> {{player.name}} </h4>
<hr style="background-color:black;" />
<span class="label label-default"><strong>Position :</strong> {{player.position}} </span><br/>
<span class="label label-primary"><strong>Jersey Number :</strong> {{player.jerseyNumber}} </span><br/>
<span class="label label-success"><strong>Date Of birth :</strong> {{player.dateOfBirth}}</span><br/>
<span class="label label-info"><strong>Nationality :</strong> {{player.nationality}} </span><br/>
<span class="label label-warning"><strong>Contract Untill :</strong> {{player.contractUntil}}</span><br/>
<span class="label label-success"><strong>Market Value :</strong> {{player.marketValue}}</span><br/>
</div>
</div>
</div>
</div>
</div>
</div>
<div *ngIf="!players?.length">
<h3>No Player Data found For the Selected Team</h3>
</div>
handle the (complete) => {} callback inside subscribe (Subscribe Docs) and set a boolean to true. Check against this boolean with your *ngIf.
So, inside your Team Component:
players:any[] = [];
loadCompleted:boolean = false;
ngOnInit(){
this.teamId = this.route.snapshot.params['id'];
this.teamCrest = this.competitionService.teamCrest;
this.getPlayers();
}
getPlayers(){
this.loadCompleted = false;
this.competitionService.getPlayers(this.teamId)
.subscribe(
player => this.players = player.players,
(error) => console.error(error),
() => this.loadCompleted = true)
);
}
then in your HTML template:
<div *ngIf="loadCompleted" class="container">
<div class="row">
<div *ngFor="let player of players" #data>
<div class="col-md-4">
<div class="well box">
<img class="avatar" src="{{teamCrest}}">
<h4> {{player.name}} </h4>
<hr style="background-color:black;" />
<span class="label label-default"><strong>Position :</strong> {{player.position}} </span><br/>
<span class="label label-primary"><strong>Jersey Number :</strong> {{player.jerseyNumber}} </span><br/>
<span class="label label-success"><strong>Date Of birth :</strong> {{player.dateOfBirth}}</span><br/>
<span class="label label-info"><strong>Nationality :</strong> {{player.nationality}} </span><br/>
<span class="label label-warning"><strong>Contract Untill :</strong> {{player.contractUntil}}</span><br/>
<span class="label label-success"><strong>Market Value :</strong> {{player.marketValue}}</span><br/>
</div>
</div>
</div>
</div>
</div>
</div>
<div *ngIf="loadCompleted && !players?.length">
<h3>No Player Data found For the Selected Team</h3>
</div>
If i understood your question, this should do what you want.
Just a side note: in your backend service, IMHO, you shouldn't return null if there aren't players for the input teamId, but an empty List/Array/whatever.
Related
I have a project in Laravel and Livewire.
This is my view displaying a list of projects submitted.
#forelse ($projects as $index => $project)
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<a href="#" wire:click="showProjectDetails({{ $project->slug }})"
class="block p-6 bg-white border border-gray-200 rounded-sm shadow-md hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700">
<h5 class="mb-2 text-2xl font-bold tracking-tight text-blue-500 dark:text-white">
{{ $project->title }}
</h5>
<p class="my-5">Bugdet Ghc500 - Ghc 700</p>
<p class="font-normal text-gray-700 dark:text-gray-400">{{ $project->description }}</p>
<ul class="flex gap-4 text-blue-600 mt-5">
<li>PHP</li>|
<li>Mobile App Development</li>|
<li>Database Management</li>|
<li>C++</li>
</ul>
</a>
</div>
#empty
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<p class="text-4xl">No Projects found</p>
</div>
#endforelse
When I click on a single project, a new view called show-project should display the details of the particular project that has been clicked.
My Livewire controller
public function showProjectDetails($slug)
{
return redirect()->route('show-project.details', $slug);
}
<a href="{{ route('show.project_details', ['slug' => $project->slug]) }}">
and web.php route can be either Controller or Livewire page.
with livewire 1.3 / alpinejs 2.x.x I make listing of data with filter text
and selection inputs and clicking on “Search” button I need to run search when
“Search” button is clicked.
But search is run when text/selection input lose focus without clicking on “Search” button.
I see it by form's wire:loading block and 1 line in log file, which I trigger in render method
That is not what I need : I need to run render method only clicking on “Search” button.
I tried to use alpinejs, but failed...
In component app/Http/Livewire/Admin/AppNews.php I have:
<?php
namespace App\Http\Livewire\Admin;
use Carbon\Carbon;
use Livewire\Component;
use App\News;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class AppNews extends Component
{
use WithPagination;
use WithFileUploads;
public $filters = [
'title' => '',
'published' => '',
];
];
public $uploaded_file_name;
public $uploadedImageFilenameData;
public $uploadedNewsImage;
protected $listeners = ['fileUpload' => 'handleFileUpload'];
public $current_news_id;
public $updateMode = 'browse';
public function render()
{
\Log::info('-1 NewsRENDER $this->filters ::' . print_r($this->filters, true));
$news_rows_count = News
::getByTitle($this->filters['title'], true)
->getByPublished($this->filters['published'], true)
->count();
$backend_per_page = Settings::getValue('backend_per_page', CheckValueType::cvtInteger, 20);
$this->emit('app_news_opened', ['mode' => 'browse', 'id' => null]);
$newsPublishedValueArray = SetArrayHeader([['key' => '', 'label' => ' -Select published- ']], News::getNewsPublishedValueArray(true));
$newsDataRows = News
::getByTitle($this->filters['title'], true)
->getByPublished($this->filters['published'], true)
->with('creator')
->orderBy('news.created_at', 'desc')
->paginate($backend_per_page);
$newsDataIds = [];
foreach ($newsDataRows as $nextNews) {
$newsDataIds[] = $nextNews->id;
}
return view('livewire.admin.app-news.container', [
'newsDataRows' => $newsDataRows,
'newsDataIds' => $newsDataIds,
'form' => $this->form,
'news_rows_count' => $news_rows_count,
'newsPublishedValueArray' => $newsPublishedValueArray,
]);
}
and in the template resources/views/livewire/admin/app-news/container.blade.php :
<article class="admin_page_container">
<div class="card form-admin-news">
<div class="card-body card-block">
<div class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</div>
...
<fieldset class="bordered text-muted p-2 m-2" x-data="{ title: '{{$filters['title']}}', published: '{{$filters['published']}}' ,
publishedItems: <?php print str_replace('"',"'",json_encode( $newsPublishedValueArray) ) ?> } ">
<div> $filters::{{ var_dump($filters) }}</div>
title::<div x-html="title"></div>
published::<div x-html="published"></div>
<legend class="bordered">Filters</legend>
<dl class="block_2columns_md m-0 p-2">
<dt class="key_values_rows_label_13">
<label class="col-form-label" for="temp_filter_title">
By title
</label>
</dt>
<dd class="key_values_rows_value_13" >
<div class="content_with_right_button">
<div
class="content_with_right_button_left_content"
wire:model.lazy="filters.title"
>
<input
class="form-control admin_control_input"
type="text"
x-model="title"
x-on:blur="$dispatch('input', title)"
id="title"
>
</div>
<div class="content_with_right_button_right_button pl-2">
<button class="btn btn-outline-secondary nowrap_block" wire:click="makeSearch( )">
{!! $viewFuncs->showAppIcon('filter') !!}Search
</button>
</div>
</div>
</dd>
</dl>
<dl class="block_2columns_md m-0 p-2">
<dt class="key_values_rows_label_13">
<label class="col-form-label" for="temp_filter_published">
By published
</label>
</dt>
<dd
class="key_values_rows_value_13"
wire:model.lazy="filters.published"
>
<select
x-model="published"
x-on:blur="$dispatch('select', published)"
id="published"
class="form-control editable_field admin_control_input"
>
<template x-for="nextPublishedItem in publishedItems">
<option :value="nextPublishedItem.key" x-text="nextPublishedItem.label"></option>
</template>
</select>
#error('form.published')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl>
</fieldset> <!-- Filters -->
...
#endif {{-- #if($updateMode=='browse')--}}
#endif {{-- #if($updateMode=='browse')--}}
#if(count($newsDataRows) > 0)
<div class="table-responsive table-wrapper-for-data-listing" x-data="selectedNewsIdsBoxXData()">
<table>
...
</table>
</div> <!-- <div class="table-responsive table-wrapper-for-data-listing"> -->
#endif {{-- #if(count($newsDataRows) > 0) --}}
#endif {{-- #if($updateMode=='browse') --}}
</div> <!-- <div class="card-body card-block"> -->
</div> <!-- <div class="card"> -->
</article> <!-- page_content_container -->
Which is the valid way?
Modified BLOCK 2:
I try another way with using of alpinejs2 : I try to use it in this case, as when public var of component is changed:
with dispatch methid when button “Search” is clicked
<div class="card form-admin-facilities" x-data="adminFacilitiesComponent()">
...
filter_name: {{$filter_name}}<br>
...
temp_filter_name: <span x-html="temp_filter_name"></span><br>
...
<fieldset class="bordered text-muted p-2 m-2">
<legend class="bordered">Filters</legend>
<div class="content_with_right_button" wire:model.lazy="filter_name">
<div class="content_with_right_button_left_content" >
<input
class="form-control admin_filter_input"
x-model="temp_filter_name"
type="text"
>
</div>
<div class="content_with_right_button_right_button pl-2" >
<button class="btn btn-outline-secondary" #click="$dispatch('input', temp_filter_name)" type="button">Search
</button>
<!-- In more complicated form can be several filter fields : text and select inputs -->
</div>
</div>
</fieldset> <!-- Filters -->
...
<script>
function adminFacilitiesComponent() {
return {
temp_filter_name:'',
and in the component I defined public $filter_name var, which is used in render method :
class Facilities extends Component
{
public $form= [
'name'=>'',
'descr'=> '',
'created_at'=> '',
'is_reopen' => false,
];
public $current_facility_id;
public $filter_name= '';
public $updateMode = 'browse';
public function render()
{
\Log::info( '-1 render Facilities $this->filter_name ::' . print_r( $this->filter_name, true ) );
$this->facility_rows_count = Facility
::getByName($this->filter_name, true)
->count();
$backend_per_page = Settings::getValue('backend_per_page', CheckValueType::cvtInteger, 20);
return view('livewire.admin.facilities.container', [
'facilityDataRows' => Facility
::orderBy('created_at', 'desc')
->getByName($this->filter_name, true)
->paginate($backend_per_page),
'facility_rows_count'=> $this->facility_rows_count
]);
}
But it does not work as I expect : entering value in text input when this input lose focus
form is rendered again. I expected form to be rendered only when I click on “Search” button
and form will be rendered with new entered value. I do not use blur event for text input and
do not understand why the form is rendered when this input lose focus?
Modified BLOCK 3:
Using x-ref= I do :
<div class="content_with_right_button" wire:model.lazy="filter_name">
<div class="content_with_right_button_left_content" >
<input
class="form-control admin_filter_input"
x-model="temp_filter_name"
x-ref="searched"
type="text"
> 1111111
</div>
<div class="content_with_right_button_right_button pl-2" >
<button class="btn btn-outline-secondary nowrap_block" wire:click="makeSearch(this.$refs.searched)" type="button">
Search
</button>
</div>
</div>
But I got error clicking on search button:
VM1983:6 Uncaught TypeError: Cannot read property 'searched' of undefined
at eval (eval at parseOutMethodAndParams (directive.js:55), <anonymous>:6:27)
at _default.parseOutMethodAndParams (directive.js:55)
Looks like it is impossible to use this.$refs. value in
wire:click="makeSearch .
I need to trigger component method
public function makeSearch($search_value='')
{
and send entered value into it.
Looks like the way I tried was invalid.
If there is a valid way?
Thanks!
In your modified block 2, you should use wire:ignore in base div of your AlpineJS component. This will make livewire ignore the component.
<div class="card form-admin-facilities" wire:ignore x-data="adminFacilitiesComponent()">
Your $dispatch() should handle setting the value when you click the button.
In order to make livewire ignore the component just add wire:ignore to your component's div in modified block 2 and then in your dispatch method you can write the logic that happens after clicking the button.
I've been trying to create a DRF API with an Angular front end for an existing project that I have. I've created a serializer for User and Device. I tried removing multiple pieces of the HTML component, managing to result in a different error, StaticInjectorError(AppModule -> DevicePostService).
I'm still pretty new to Angular so what it seems like the error is coming from is the fact that my devicepostservice is not getting served to the web page for some reason.
Console error:
[Error] Error: Template parse errors:
Unexpected character "<" ("
<div class="col-sm-4">
<button (click)="login()" class="btn btn-primary">Log In</button
[ERROR ->]</div>
<div class="col-sm-12">
<span *ngFor="let error of _userService.errors.non_field_errors""): ng:///AppModule/AppComponent.html#15:2
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("
<div class="col-sm-4">
<button (click)="login()" class="btn btn-primary">Log In</button
[ERROR ->]</div>
<div class="col-sm-12">
<span *ngFor="let error of _userService.errors.non_field_errors""): ng:///AppModule/AppComponent.html#15:2
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (" <span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span>
</div>
[ERROR ->]</div>
<div class="row" *ngIf="_userService.token">
<div class="col-sm-12">You are logged in as {{ "): ng:///AppModule/AppComponent.html#19:0
_preparseLoadedTemplate (vendor.js:24658)
normalizeTemplate (vendor.js:24635)
loadDirectiveMetadata (vendor.js:26827)
(anonymous function) (vendor.js:34471)
forEach
(anonymous function) (vendor.js:34470)
forEach
_loadModules (vendor.js:34467:83)
_compileModuleAndComponents (vendor.js:34445)
compileModuleAsync (vendor.js:34405)
bootstrapModule (vendor.js:53721)
./src/main.ts (main.js:326:116)
__webpack_require__ (runtime.js:79)
(anonymous function) (main.js:339)
__webpack_require__ (runtime.js:79)
checkDeferredModules (runtime.js:46)
webpackJsonpCallback (runtime.js:33)
Global Code (main.js:1)
App.component.html
<h2>Log In</h2>
<div class="row" *ngIf="!_userService.token">
<div class="col-sm-4">
<label>Username:</label><br />
<input type="text" name="login-username" [(ngModel)]="user.username">
<span *ngFor="let error of _userService.errors.username"><br />
{{ error }}</span></div>
<div class="col-sm-4">
<label>Password:</label><br />
<input type="password" name="login-password" [(ngModel)]="user.password">
<span *ngFor="let error of _userService.errors.password"><br />
{{ error }}</span>
</div>
<div class="col-sm-12">
<span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span>
</div>
</div>
<div class="row" *ngIf="_userService.token">
<div class="col-sm-12">You are logged in as {{ _userService.username }}.<br />
Token Expires: {{ _userService.token_expires }}<br />
<button (click)="refreshToken()" class="btn btn-primary">Refresh Token</button>
<button (click)="logout()" class="btn btn-primary">Log Out</button>
</div>
</div>
<!--
<h2 class="mt-3">Devices</h2>
<div *ngFor="let device of devices">
<div class="row mb-3">
<label class="col-md-2">Owner:</label>
<div class="col-md-2 mb-1">{{ device.owner }}</div>
<label class="col-md-2">Brand:</label>
<div class="col-md-6">{{ device.brand }}</div>
<div class="col-md-12">{{ device.name }}</div>
</div>
</div>-->
App.component.ts
import {Component, OnInit} from '#angular/core';
import {DevicePostService} from './device_post.service';
import {UserService} from './user.service';
import {throwError} from 'rxjs';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
/**
* An object representing the user for the login form
*/
public user: any;
public devices;
public new_device: any;
constructor(private _devicePostService: DevicePostService, private _userService: UserService) { }
ngOnInit() {
this.getDevices();
this.new_device = {};
this.user = {
username: '',
password: ''
};
}
getDevices() {
this._devicePostService.list().subscribe(
data => {
this.devices = data;
},
err => console.error(err),
() => console.log('done loading devices')
)
}
updateDevice () {
this._devicePostService.create(this.new_device, this.user.token).subscribe(
data => {
this.getDevices();
return true;
},
error => {
console.error('Error saving!');
return throwError(error);
}
);
}
login() {
this._userService.login({'username': this.user.username, 'password': this.user.password});
}
refreshToken() {
this._userService.refreshToken();
}
logout() {
this._userService.logout();
}
}
Seems like you have a basic syntax error in your template
<button (click)="login()" class="btn btn-primary">Log In</button
should be
<button (click)="login()" class="btn btn-primary">Log In</button>
(note the final '>' character)
I have an angular app that has the following ng-repeat:
<div ng-repeat="detail in mpttdetails">
<div ng-if="detail.category.id == {{node.id}}" class="list-group">
{%verbatim%}
<li class="list-group-item" >
<div class="row">
<div class=".col-lg-2 col-md-2 col-sm-2">
{{detail.student_academic_credit.course_name}}
</div>
<div class=".col-lg-4 col-md-4 col-sm-3">
{{detail.student_academic_credit.title}}
</div>
<div class=".col-lg-2 col-md-2 col-sm-2">
{{detail.student_academic_credit.credit}}
</div>
<div class=".col-lg-2 col-md-2 col-sm-2">
{{detail.student_academic_credit.final_grade}}
</div>
<div class=".col-lg-2 col-md-2 col-sm-3">
{{detail.student_academic_credit.term}}
</div>
</div>
</li>
{%endverbatim%}
</div>
</div>
My mpttservice here is a service that fetches data from a django app. Here i would like to have a bootstrap badge as:
<span class="badge badge-info">{{sum}}</span>
just above the ng-repeat such that it adds all the {{detail.student_academic_credit.credit}} from the list. How do i achieve this since all the details are inside the ng-repeat??
I suggest you use a couple of filters: Angular's filter for filtering details based on their categoryId and one custom filter for summing credits.
app.filter('sumCredits', function () {
return function (details) {
var sum = 0;
details.forEach(function (item) {
sum += item.student_academic_credit.credit;
});
return sum;
};
});
<span class="badge badge-info"
ng-bind="mpttdetails | filter:{catagory:{id:node.id}} | sumCredits">
</span>
<div ng-repeat="detail in mpttdetails | filter:{catagory:{id:node.id}}">
{%verbatim%}
<li class="list-group-item">
...
See, also, this short demo.
In the controller that has the service injected, loop through just like ng-repeat is doing and add to your $scope.sum.
app.controller('WhateverCtrl', function($scope, mptt) {
// Assuming it's an ajax call
mptt.getDetails().success(function(mpttdetails) {
$scope.mpttdetails = mpttdetails;
// Set sum on scope
var sum = 0;
angular.forEach(mpttdetails, function(detail) {
sum = sum + detail.student_academic_credit.credit;
});
$scope.sum = sum;
});
});
In this example I want to use knockout.js to allow the "Expand" link to be clicked and have its text changed to "Collapse". I also want to set the make the jobDetails section visible. This is a very general question of how to get knockout.js to specifically modify the DOM of the "current" item in a list using a click handler.
<script type="text/html" id="job-template">
<div class="jobContainer">
<label data-bind="text: JobTitle"></label>
<label data-bind="text: CompanyName"></label>
<div class="jobDetails">
<label data-bind="text: City"></label>
<label data-bind="text: State"></label>
</di>
<div>
<a class="expand" href="#" data-bind="click: ???">Expand</a>
</div>
</div>
</script>
This is very straight forward with KO. Here's a simple way to do it. FYI I had to fix your markup slightly.
<div>
<div class="jobContainer">
<label data-bind="text: JobTitle"></label>
<label data-bind="text: CompanyName"></label>
<div class="jobDetails" data-bind="visible: expanded">
<label data-bind="text: City"></label>
<label data-bind="text: State"></label>
</div>
<div>
<a class="expand" href="#" data-bind="click: toggle, text: linkLabel">Expand</a>
</div>
var viewModel = function() {
this.JobTitle = ko.observable("some job");
this.CompanyName = ko.observable("some company");
this.City = ko.observable("some city");
this.State = ko.observable("some state");
this.someValue = ko.observable().extend({ defaultIfNull: "some default" });
this.expanded = ko.observable(false);
this.linkLabel = ko.computed(function () {
return this.expanded() ? "collapse" : "expand";
}, this);
this.toggle = function () {
this.expanded(!this.expanded());
};
};
http://jsfiddle.net/madcapnmckay/XAzW6/
Hope this helps.